Answer the question
In order to leave comments, you need to log in
Yii2. How to sequentially link 3 tables?
There was a problem.
There are 3 tables Tests, Questions, Answers, which are connected in series.
I found a picture for an example, but I have 1-to-many connections.
How can I do it in Yii2 in such a way that I would display data from all 3 tables in one query, while maintaining the correct hierarchy at the output (using asArray())?
In the Test model, I wrote the following code, but this is not correct, apparently.
public function getQuestion()
{
return $this->hasMany(Question::className(), ['test_id' => 'id']);
}
public function getAnswer()
{
return $this->hasMany(Answer::className(), ['question_id' => 'id'])
->viaTable(Question::tableName(), ['test_id' => 'id']);
}
$test = Test::find()->asArray()->joinWith('question')->where(['tests.id'=>$id])->all();
Array
(
[id] => 2
[name] => Тестовый тест №2
[question] => Array
(
[0] => Array
(
[id] => 1
[test_id] => 2
[question] => сколько будет 2+3?
)
[1] => Array
(
[id] => 3
[test_id] => 2
[question] => Столица России?
)
)
)
Array
(
[id] => 2
[name] => Тестовый тест №2
[question] => Array
(
[0] => Array
(
[id] => 1
[test_id] => 2
[question] => сколько будет 2+3?
[answer] => Array
(
[0] =>Array
(
[id] => 1
[question_id] => 1
[answer] => 4
[is_right_answer] => false
)
[1] =>Array
(
[id] => 2
[question_id] => 1
[answer] => 5
[is_right_answer] => true
)
[2] =>Array
(
[id] => 3
[question_id] => 1
[answer] => 6
[is_right_answer] => false
)
)
[1] => Array
(
[id] => 3
[test_id] => 2
[question] => Столица России?
[answer] => Array(...)
)
)
)
Answer the question
In order to leave comments, you need to log in
1. if you have hasMany, use the plural - getQuestions, getAnswers
2. ->joinWith(['questions', 'questions.answers'])
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question