cviebrock / eloquent-taggable

Easily add the ability to tag your Eloquent models in Laravel.
MIT License
537 stars 72 forks source link

Can i use Eager Loading? #80

Closed WL1981 closed 5 years ago

WL1981 commented 6 years ago

In my Laravel blade template i use a foreach in a foreach loop which is not very efficient. Is there a way i can use eager loading?

@foreach( $files as @file ) {{ $variant->filename }} @foreach( App\FileEntry::Variants( $file->id ) as $variant ) {{ $variant->filename }} @endforeach @endforeach

cviebrock commented 6 years ago

I'm not sure how this relates to the package. But you can always eager-load the relationships ... ideally in your controller before you pass things to a view. I'm a bit unclear which models have been tagged, but maybe you want something like $files->with('variants') in your controller?

cviebrock commented 5 years ago

Closing due to no response. Feel free to re-open or comment if you are still having issues.

judgej commented 5 years ago

I think the answer to this question is, yes:

$yourModelQuery->with('tags')->get();

When retrieving a a big bunch of model instances, and when you know you will be needing all the related tags for each of them, then eager loading can lower the number of database queries from potentially hundreds, to just two or three.

This should be perhaps mentioned in the documentation, since it can have such a significant hit on performance.