选择带有关系的查询并没有在laravel eloquent中给出结果

时间:2018-05-25 11:35:18

标签: php laravel eloquent

records = Student::with(array('Mark' => function($marks)
    {
    $marks->select(DB::raw('sum(obtain_marks)'))->with(array('Subject' => function($subject){
    $subject->orderby('subject_name')->select(DB::raw('count(subjects.id)','sum(total_marks)','subject_name'));
        }));
    }))->where('id', $id)->get();

为什么这不执行?

它在mysql中工作 选择count(subjects.id),sum(subjects.total_marks),sum(marks.obtain_marks),subjects.subject_name来自Students.id = marks.student_id上的学生内部联接标记subjects.id = marks.subject_id where students.id = 20 group by subjects.subject_name;它在mysql中工作。

1 个答案:

答案 0 :(得分:0)

在“选择”中,您必须选择具有本地密钥的列

$records = Student::with(['Mark' => function($marks){
    $marks->select(DB::raw('sum(obtain_marks)'), 'Subject_id' /* same Problem here ->select('subject_id')*/)->with(['Subject' => function($subject){
        $subject->orderby('subject_name')
                ->select(DB::raw('count(subjects.id)','sum(total_marks)','subject_name'));
    }]);
}])
->where('id', $id)
->select('Mark_id') // you must select foreign key column to use relationship
->get();