1
votes

I have three table:

Teacher

id

name

family_name

ClassRoom

class_name

teacher_id

Student

name

family_name

Teacher have one to many relation with ClassRoom

Student have many to many relation with ClassRoom

how can i retrieve all Students of a Teacher using Eloquent methods without using foreach?

2

2 Answers

2
votes
$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
votes

in your teacher model create a new relation like below:

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

now you just query the student like below:

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