Laravel 5.1 > split nested lazy loading

194 Views Asked by At

Is it possible to split a nested lazy loading method?

I´ve got

$this->user->load('latestConversations.latestMessage.user')

I´d also like to load all Users assigned to latestConversations so something like this would be nice:

$this->user->load('latestConversations.['users', 'latestMessage.user']')

Here is a workaround

$this->user->load('latestConversations.latestMessage.user')
$this->user->load('latestConversations.users')

But then latestConversations are queried two times.

1

There are 1 best solutions below

1
On BEST ANSWER

If you leave the parentheses on the relation method you can just add on whatever you want to the query, and then manually set the relation using setRelation(). I haven't tested it but something like this should work:

$latestConversations = $this->user
                            ->latestConversations()
                            ->with('latestMessage.user', 'users')
                            ->get();
$this->user->setRelation('latestConversations', $latestConversations);

// then you should be able to just access it normally:
return $this->user->latestConversations;