My question may be confuse because I've started learning Laravel.
Can I use eloquent model property in subquery of with() function?
I have classes
, students
, and grades
tables. I wish to get
$classes = [{id:1, name:'maths', students:[{id:2, name: john,
grade:B},{id:1, name: Mac, grade:C}]}, {id:2, name:'physics',
students:[{id:2, name: john, grade:null},{id:1, name: Mac,
grade:null}]}]
for example:
$classes = Class::with(['students' => function($query){
->leftJoin('grades', 'grades.student_id', '=', 'students.id')
}])->get()->toJSON();
This query doesn't select correct grades of related classes. I wish to use class::id = grades.class_id
in join condition.
I use leftJoin because some class may not have released its grade.
You need to do it this way:
$classes = Class::with(['students' => function($query){
->leftJoin('grades', function($join) {
$join->on('grades.student_id', '=', 'students.id');
$join->on('grades.class_id', '=', 'class.id');
})
}])->get()->toJSON();
Finally I got solutions, even though, not best solution but it worked. Thank @Marcin Nabialek and @lukasgeiter. It is just simply to through pivot table class_student
.
$classes = Class::with(['students' => function($query){
$query->leftJoin('grades', function($join) {
$join->on('grades.student_id', '=', 'students.id');
$join->on('students.id', '=', 'class_student.student_id');
$join->on('class_student.class_id', '=', 'grades.class_id');
})
}])->get()->toJSON();
It took too much time bcoz passing through many join tables.
Hoping to get better solutions.