【问题标题】:retrieve data from 3 tables How to retrieve data from the last table using the first one in Laravel从 3 个表中检索数据 如何使用 Laravel 中的第一个表从最后一个表中检索数据
【发布时间】:2017-04-12 13:18:41
【问题描述】:

我有三张桌子:

老师

身份证

名字

家庭名称

教室

类名

teacher_id

学生

名字

家庭名称

教师与教室是一对多的关系

学生与教室有多对多的关系

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

【问题讨论】:

标签: php laravel eloquent


【解决方案1】:
$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

【讨论】:

  • BadMethodCallException with message '方法列表不存在。
  • 尝试 pluck('students') 代替列表
【解决方案2】:

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

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

现在您只需像下面这样查询学生:

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

【讨论】:

  • hasManyThrouh 仅用于三个具有一对多关系的表我有一对多和多对多
猜你喜欢
  • 1970-01-01
  • 2016-03-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-15
  • 1970-01-01
  • 1970-01-01
  • 2020-12-14
相关资源
最近更新 更多