简体   繁体   中英

Laravel - Repetitive query in blade view - Reducing number of queries

I am in a situation where I have a lot of relationships and it is becoming a problem as it slows down a site when I do a lot of queries.

For instance, I am doing a foreach loop for all blogs and getting the user who made the blog.

@foreach ($blogs as $blog)
    <a href="{{ route('blog.view', str_slug($blog->title)) }}">{{ $blog->title }}</a>

    {{ $blog->created_at }}

    <a href="{{ viewProfile($blog->user) }}"><{{ $blog->user->username }}/a>

    Last Commenter:
    <a href="{{ viewProfile($blog->lastCommenter()->user) }}">
        {{ $blog->lastCommenter()->user->username }}
    </a>

@endforeach

That alone is more than 50+ queries.. And if there are like 100 blogs, the number of queries is way off.

How can I avoid doing this? I have stored it in a variable in this view but I don't want to really put any PHP code in a blade file. How can I avoid doing this? I have tried using cache in database but that's also doing a few queries to the cache table in database. I am also using eager loading which has helped a lot. But how can I best do this kind of things?

Thank you very much for your response in advance.

That is called N+1 problem. You should learn how to use Eager loading and load relations first. Then iterate over collection to display data to the user.

An example of eager loading of multiple relations from documentation:

$books = App\Book::with('author', 'publisher')->get();

An example and tutorial suggested by @Achraf Khouadja:

$blogs = blog::with('lastCommenter', 'user')->get();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM