我有多对多关系的 students
和 subjects
表(数据透视表是 student_subject)。
学生模型
public function subjects()
{
return $this->belongsToMany(Subject::class, 'student_subject');
}
学科模型
public function students()
{
return $this->belongsToMany(Student::class, 'student_subject');
}
这里我想要特定的学生科目计数。我尝试了以下方法,效果很好,但我想要最有效的方法。
1.
$student = Student::find($id);
$subject_count = $student->subjects()->count();
我通过 laravel 调试器检查了 SQL 查询,它显示如下
select * from `students` where `students`.`id` = '10' limit 1
select count(*) as aggregate from `subjects` inner join `student_subject` on `subjects`.`id` = `student_subject`.`subject_id` where `student_subject`.`student_id` = 10 and `subjects`.`deleted_at` is null
$student = Student::withCount('subjects')->find($id);
$subject_count = $student->subjects_count;
我通过 laravel 调试器检查了 SQL 查询,它显示如下
select `students`.*, (select count(*) from `subjects` inner join `student_subject` on `subjects`.`id` = `student_subject`.`subject_id` where `students`.`id` = `student_subject`.`student_id` and `subjects`.`deleted_at` is null) as `subjects_count` from `students` where `students`.`id` = '10' limit 1
$student = Student::find($id);
$subject_count = $student->loadCount('subjects')->subjects_count;
我通过 laravel 调试器检查了 SQL 查询,它显示如下
select * from `students` where `students`.`id` = '10' limit 1
select `id`, (select count(*) from `subjects` inner join `student_subject` on `subjects`.`id` = `student_subject`.`subject_id` where `students`.`id` = `student_subject`.`student_id` and `subjects`.`deleted_at` is null) as `subjects_count` from `students` where `students`.`id` in (10)
$student = Student::find($id);
$subject_count = DB::table('student_subject')->where('student_id', $student->id)->count();
我通过 laravel 调试器检查了 SQL 查询,它显示如下
select * from `students` where `students`.`id` = '10' limit 1
select count(*) as aggregate from `student_subject` where `student_id` = 10
根据上面的方法哪一种最好,为什么?或者是否还有其他不同的最佳方式?
答案 0 :(得分:1)
执行 relation()->count()
可能会更快。
但如果您只需要计数,那么 withCount()
在内存消耗方面应该会更好。