Php 从3个表检索数据如何使用Laravel中的第一个表从最后一个表检索数据
我有三张桌子: 老师 身份证 名字 姓 教室 类名 教师id 学生 名字 姓 教师与课堂有一对多的关系 学生与课堂有着多对多的关系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
如何在不使用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仅用于具有一对多关系的三个表我有一对多和多对多