我有三张桌子:
教师
ID
名称
FAMILY_NAME
教室
CLASS_NAME
teacher_id
学生
名称
FAMILY_NAME
教师与ClassRoom有一对多的关系
学生与ClassRoom有很多关系
如何在不使用foreach的情况下使用Eloquent方法检索教师的所有学生?
答案 0 :(得分:2)
$teacher = Teacher::with('classrooms.students')->find($someId); //eager load
$studentsArray = $teacher->classrooms->pluck('students'); //array of students with duplicates
$students = (new Collection($studentsArray))->collapse()->unique(); //collection of unique students
答案 1 :(得分:0)
创建一个如下所示的新关系:
public function students()
{
return $this->hasManyThrough(Student::class, ClassRoom::class);
}
现在您只需查询下面的学生:
$teacher = Teacher::where('id', '1')->first();
$students = $teacher->students;