Support the ongoing development of Laravel.io →
posted 11 years ago
Eloquent

Let's say a school has many teachers, and each teacher has many pupils.

Is there an easy way of returning all pupils for the school i.e. $school->teachers->pupils ?

I understand that $school->teachers will return a collection and you can iterate over that to find the pupils for each teacher and then somehow combine them but it seems a bit messy.

What's the best way of achieving this?

Last updated 3 years ago.
0

You can use something like this

School::with('teachers','teachers.pupils')->get();

Just adust the names of your relationships

Last updated 3 years ago.
0

pixelpeter said:

You can use something like this

School::with('teachers','teachers.pupils')->get();

Just adust the names of your relationships

That will eager load pupils but not combine them.

I think the only way for now could be something like this:

Pupil::whereIn('teacher_id', function($query) use ($school) {
    $query->select('id')->from('teachers')->where('school_id', $school->id);
});
Last updated 3 years ago.
0

cheers popolla your suggestion worked!

maybe pushing it here but is there any way to add in another level?!

something like area->school->teachers->pupil ?

thanks again.

Last updated 3 years ago.
0

by the way for anyone looking in I had to add ->get() onto the end of popolla's query otherwise there was a recursion error

Last updated 3 years ago.
0

lainga9 said:

maybe pushing it here but is there any way to add in another level?!

something like area->school->teachers->pupil ?

Try this one:

$pupils = Pupil::whereIn('teacher_id', function($query) use ($area) {
    $query->select('teachers.id')->from('teachers')
        ->join('schools', 'teachers.school_id', '=', 'schools.id')
        ->where('schools.area_id', '=', $area->id);
})->get();
Last updated 3 years ago.
0

works perfectly - thanks a lot!

Last updated 3 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

lainga9 lainga9 Joined 12 Feb 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.