2016-11-28 64 views
1

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

教师

ID

FAMILY_NAME

课室

CLASS_NAME

teacher_id

学生

FAMILY_NAME

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

学生有男人y与课室有很多关系

如何检索教师的所有学生使用Eloquent方法而不使用foreach?

+0

这是在文档:https://开头laravel.com/docs/master/eloquent-relationships#has-many-through – mopo922

回答

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

BadMethodCallException与消息'方法列表不存在。 – Sia

+1

试试pluck('students')而不是列表 –

+0

非常感谢alex alex为我工作 – Sia

0
在你的老师模型

创建像下面一个新的关系:

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

现在你只查询像下面的学生:

$teacher = Teacher::where('id', '1')->first(); 
$students = $teacher->students; 
+0

hasManyThrouh只用于三个表的一对多关系我有一对多和多对多 – Sia

相关问题