Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/295.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 从3个表检索数据如何使用Laravel中的第一个表从最后一个表检索数据_Php_Laravel_Eloquent - Fatal编程技术网

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

Php 从3个表检索数据如何使用Laravel中的第一个表从最后一个表检索数据,php,laravel,eloquent,Php,Laravel,Eloquent,我有三张桌子: 老师 身份证 名字 姓 教室 类名 教师id 学生 名字 姓 教师与课堂有一对多的关系 学生与课堂有着多对多的关系 如何在不使用foreach的情况下使用雄辩的方法检索教师的所有学生?在教师模型中创建如下新关系: $teacher = Teacher::with('classrooms.students')->find($someId); //eager load $studentsArray = $teacher->classrooms->pluck('stu

我有三张桌子:

老师

身份证

名字

教室

类名

教师id

学生

名字

教师与课堂有一对多的关系

学生与课堂有着多对多的关系


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

在教师模型中创建如下新关系:

$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;
现在您只需查询学生,如下所示:

public function students()
{
    return $this->hasManyThrough(Student::class, ClassRoom::class);
}
$teacher = Teacher::where('id', '1')->first();
$students = $teacher->students;

这在文档中:BadMethodCallException with message'方法列表不存在。请尝试Pull('students'),而不是listshasManyThrouh仅用于具有一对多关系的三个表我有一对多和多对多