1

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.

2 Answers 2

0

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();
Sign up to request clarification or add additional context in comments.

3 Comments

Hi Marcin, thank for your help, but I aldy tried it. It result this error SQLSTATE[HY000]: General error: 1 no such column: class.id
@RyanExlay It should probably be classes.id (or whatever your table name for the Class model is)
@lukasgeiter, same error landed. Anyway, thank for your help. I can't call class property in students. I am trying to use hasManyThrough relations student->class->grade relations.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.