У меня есть 5 связанных таблиц:
course{id, name, ...} у нее модель Course
lesson{id, name, course_id, ...} у нее модель Lesson
theme{id, name, lesson_id, ...} у нее модель Theme
material{id, name, theme_id, ...} у нее модель Material
test_answer{..., material_id, ...} у нее модель TestAnswer
Я сделал таким образом:
public function getMaterial($material_id)
{
return Material::find()->where(['id' => $material_id, 'is_active' => 1])->orderBy('sort')->all();
}
public function getTheme($theme_id)
{
return Theme::find()->where(['id' => $theme_id, 'is_active' => 1])->orderBy('sort')->all();
}
public function getLesson($lesson_id)
{
return Lesson::find()->where(['id' => $lesson_id, 'is_active' => 1])->orderBy('sort')->all();
}
public function getCourse($course_id)
{
return Course::find()->where(['id' => $course_id, 'is_active' => 1])->orderBy('sort')->all();
}
public function getAnswerDestination($material_id)
{
$material = self::getMaterial($material_id);
$theme_id = yii\helpers\ArrayHelper::getColumn($material, 'theme_id');
$theme = self::getTheme($theme_id);
$lesson_id = yii\helpers\ArrayHelper::getColumn($theme, 'lesson_id');
$lesson = self::getLesson($lesson_id);
$course_id = yii\helpers\ArrayHelper::getColumn($lesson, 'course_id');
$course = self::getCourse($course_id);
$course_name = yii\helpers\ArrayHelper::getColumn($course, 'name');
$lesson_name = yii\helpers\ArrayHelper::getColumn($lesson, 'name');
$theme_name = yii\helpers\ArrayHelper::getColumn($theme, 'name');
$result_course = (object) [
'id' => $course_id[0],
'name' => $course_name[0],
];
$result_lesson = (object) [
'id' => $lesson_id[0],
'name' => $lesson_name[0],
];
$result_theme = (object) [
'id' => $theme_id[0],
'name' => $theme_name[0],
];
$result = (object) [
'course' => $result_course,
'lesson' => $result_lesson,
'theme' => $result_theme,
];
return $result;
}
И он выводит объект такого вида
Но тут я использую сразу 4 sql запроса можно ли сделать что то наподобие этого:
SELECT course.name AS course , lesson.name AS lesson,theme.name AS theme
FROM testanswer
INNER JOIN materials ON materials.id= testanswer.material_id
INNER JOIN theme ON theme.id= materials.theme_id
INNER JOIN lesson ON lesson.id = theme.lesson_id
INNER JOIN course ON course.id=lesson.course_id