有没有一种雄辩的方法可以从关系表中获得平均值?我这里有 2 张桌子。
我可以使用 withAvg
获得所有考试的平均值,但我还想获得每次考试的平均值(参见预期结果)。有人可以给一个想法如何做到这一点?谢谢
型号:
Student (students)
- id
- name
Exam (exams)
- id
- title
- is_correct
- student_id
StudentExam (studentExams)
- id
- section
我已经尝试过这个并且它工作正常。
StudentExam::whereSection(1)
->with('exams')
->withAvg('exams AS total_avg_exams', 'is_correct);
->first();
结果为:
{
section: 1,
total_avg_exams: 0.63,
exams: [{},{}],
}
预期结果是:
{
section: 1,
total_avg_exams: 0.63,
exams: [
{
avg_exams: 0.83,
...
},
{
avg_exams: 0.63,
...
}
]
}
答案 0 :(得分:0)
您需要在 with 语句中对考试进行分组。我假设所有相关的考试都具有相同的标题,所以应该是这样的。
use Illuminate\Support\Facades\DB;
StudentExam::whereSection(1)
->with(['exams' => function($query){
//You need the title for grouping
//You will need the student id for the eager loading so relation works
//is_correct is needed for the query
return $query->select(
'title',
'student_id',
'is_correct',
DB::raw('avg(is_correct) as total_avg_exams'))
->groupBy('title');
}])
->withAvg('exams AS total_avg_exams', 'is_correct');
->first();