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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了从3个表中检索数据如何使用Laravel中的第一个表从最后一个表中检索数据相关的知识,希望对你有一定的参考价值。

我有三张桌子:

老师

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;

以上是关于从3个表中检索数据如何使用Laravel中的第一个表从最后一个表中检索数据的主要内容,如果未能解决你的问题,请参考以下文章