从3个表中检索数据如何使用Laravel中的第一个表从最后一个表中检索数据

时间:2016-11-28 18:04:52

标签: php laravel eloquent

我有三张桌子:

教师

ID

名称

FAMILY_NAME

教室

CLASS_NAME

teacher_id

学生

名称

FAMILY_NAME

教师与ClassRoom有一对多的关系

学生与ClassRoom有很多关系

如何在不使用foreach的情况下使用Eloquent方法检索教师的所有学生?

2 个答案:

答案 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;
相关问题