Answer the question
In order to leave comments, you need to log in
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);
}
public function question_data()
{
return $this->hasOne('App\Question', 'id', 'question_id');
}
Answer the question
In order to leave comments, you need to log in
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');
}
User::find(1)->questions;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question