untymage's avatar

Does eager loading only needed for one-to-many relationships?

Excuse me, When should i use eager loading on my relationships ? I have some many to many relationship but it doesnt affect the number of queries, For example, Tags has many to many (polymorphic) to another models, But no matter i eager load ($with = ['relation']) the relation the number of queries is big, my codes: https://laracasts.com/discuss/channels/laravel/n1-when-using-wherepivot

So the purpose of eager loading for only one to many relation for reducing queries ?

0 likes
4 replies
ahmeddabak's avatar

Thread::with('tags')->get(); will load all threads and all tags with all pivot tables in two or three quires

Swaz's avatar

The type of relation doesn't matter. You should use eager loading anytime you are looping through data and accessing a relation on the current item being looped.

For example:

@foreach($items as $item)
    {{ $item->user->email }}
@endforeach

The "user" relation should be eager loaded in this case:

$items = Item::with('user')->get();
untymage's avatar

@swaz Say a Thread belongsToMany Tag, If the thread have 3 tags in pivot table, Does it matter if i eager load the relation? Is it normal the thread perform 3 query to get that tags ($thread->tags) ? Does it affect the query if i eager load this ?

Swaz's avatar
Swaz
Best Answer
Level 20

If you are currently viewing a thread. Then it makes no difference if you eager load or not, because the tags relation is only being called once.

If you are looping through the threads, and showing each tag like this:

@foreach($threads as $thread)
    {{ $thread->name }}

    @foreach($thread->tags as $tag)
        {{ $tag->name }}
    @endforeach
@endforeach

Then you would want to eager load, otherwise it will load the tag relation on each iteration of the loop.

Please or to participate in this conversation.