K
K
klinnov2016-09-25 17:54:50
Laravel
klinnov, 2016-09-25 17:54:50

How to build relationships between models?

Hello!
There are 3 tables and, accordingly, 3 models. One of them as a link between the other two.
These models are:
- User
- Question
- QuesionUser
There is a query that should get all the questions that are attached to the user.
I do it like this:
UserController:

/**
     * Get user questions
     *
     * @param int $id User id
     * @param int $form_id Form id
     * @return Response
     */
    public function getQuestionsByForm($id, $form_id): Response
    {
        $questions =  QuestionUser::where('user_id', $id)->where('form_id', $form_id)
            ->with('question_data')
            ->get();
        $data = [];
        foreach ($questions as $question) {
            array_push($data, $question['question_data']);
        }
        return response([
            'data' => $data
        ], 200);
    }

app\QuestionUser.php:
public function question_data()
    {
        return $this->hasOne('App\Question', 'id', 'question_id');
    }

Now the question is how to do it right?
Thank you!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
WebDev, 2016-09-25
@klinnov

Everything is much easier.
Models need 2:
User and Question
The link table between them should be called question_user and have user_id and question_id fields.
In the User model, register the relationship:

public function questions()
{
    return $this->belongsToMany('Models\Question');
}

Now you can get user questions, for example, like this
User::find(1)->questions;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question