簡體   English   中英

從3個表中檢索數據如何在Laravel中使用第一個表從最后一個表中檢索數據

[英]retrieve data from 3 tables How to retrieve data from the last table using the first one in Laravel

我有三個表:

老師

ID

名稱

課堂

班級名稱

teacher_id

學生

名稱

老師與ClassRoom有一對多關系

學生與ClassRoom有很多關系

如何在不使用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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM