我有三张桌子:
老师
ID
那么
姓
课堂
班级名称
teacher_id
学生
那么
姓
教师与ClassRoom有一对多的关系
学生与ClassRoom有很多关系
如何在不使用foreach的情况下使用Eloquent方法检索所有教师的学生?
$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
在您的教师模型中创建一个新的关系,如下所示:
public function students()
{
return $this->hasManyThrough(Student::class, ClassRoom::class);
}
现在您只需查询下面的学生:
$teacher = Teacher::where('id', '1')->first();
$students = $teacher->students;