8

Let's say I have these relationships

class Invitation
{
    public function invitedPeople()
    {
        return $this->belongsTo('App\Person', 'personID');
    }
}

class Person 
{
    public function apartments()
    {
        return $this->belongsToMany('App\Apartment', 'apartment_person', 'personID', 'apartmentID');        
    }
}

class Apartment 
{
    public function city()
    {
        return $this->belongsTo('App\City', 'cityID');
    }
}

My question here is, how many nested levels can we have when using Laravel eager loading? I've tried this query and it's not working, can someone suggest a work around for this?

return Invitation::with(['invitedPeople', 'invitedPeople.apartments', 'invitedPeople.apartments.city'])
Luis Deras
  • 1,239
  • 2
  • 19
  • 48
  • You can nest as many levels as you want. Define "not working", as that should work fine. The only thing I see is that you did not call `->get()` at the end. – patricus Mar 17 '16 at 19:44
  • 1
    There is no limit but you can optimize this by doing `Invitation::with(['invitedPeople.apartments.city'])`. – user1669496 Mar 17 '16 at 19:45
  • @user3158900 Invitation::with('invitedPeople.apartments.city']) would do three joins including invitedPeople, apartments and city? – Luis Deras Mar 17 '16 at 19:45
  • 3
    Yes and no. It doesn't use joins, but it would eager load all the data you need. – user1669496 Mar 17 '16 at 19:49

1 Answers1

10

Change it to

 return Invitation::with('invitedPeople.apartments.city')->get()

It will eager load all the related data for you. You missed the get() function. You can nest as deep as it can go.

oseintow
  • 7,221
  • 3
  • 26
  • 31