TomS
TomS

Reputation: 511

Selecting over multiple relations in Laravel

I have a podcast application with Podcast objects being put together in Lists. In a List there can be multiple Podcast objects and a Podcast can be member of multiple Lists. (n:m relation).

In addition to that, List objects are grouped in Groups, maybe Genres. A List can be included in multiple Groups and a Group can have multiple Lists.

All the necessary hasMany methods are implemented and are basically working fine.

I want to write a Laravel query (currently using php artisan tinker) which returns all Groups with their Lists and with all the Podcasts per List. I know I can do it in a multi-step process, but I'd like to avoid the N+1 problem and get all the information in one go.

Later then, I'll map over the resulting collection and process Group by Group, in every Group then List by List and for every List, I'll show Podcast information.

Is it a good idea to get all this information with one query? (If so, how could this be done?) If not, is there a rule of thumb when to use eager loading and when to accept the N+1 problem?

I'm quite new to Laravel and do not yet have the gut feeling when to use which technology...

Upvotes: 0

Views: 43

Answers (1)

the_hasanov
the_hasanov

Reputation: 843

For eager loading multiple relationships you may use "dot" syntax.

Group::with('lists.podcasts')->get();

Upvotes: 1

Related Questions