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

问题描述 投票:1回答:2

我有三张桌子:

老师

ID

那么

课堂

班级名称

teacher_id

学生

那么

教师与ClassRoom有一对多的关系

学生与ClassRoom有很多关系

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

php laravel eloquent
2个回答
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

0
投票

在您的教师模型中创建一个新的关系,如下所示:

public function students()
{
    return $this->hasManyThrough(Student::class, ClassRoom::class);
}

现在您只需查询下面的学生:

$teacher = Teacher::where('id', '1')->first();
$students = $teacher->students;
© www.soinside.com 2019 - 2024. All rights reserved.