P
P
photosho2016-03-02 22:05:12
Laravel
photosho, 2016-03-02 22:05:12

How to optimize database access?

Hello. There is such a situation: you need to display a page with a list of articles, and there are quite a few articles on this page, within 20. I read them all from the database. Let's say this:
Post::orderBy('id', 'desc')->take(20)->get();
Next, in the same list, you need to display the number of comments for each article. It turns out that foreachfor each article, you still need to execute a request to get the number of comments for it. For 20 articles, this is another 20 requests. Kind of too much. Are there options to minimize the number of requests?
I read about "greedy loading", but this, it seems, is not the case ...

Answer the question

In order to leave comments, you need to log in

4 answer(s)
A
Andrzej Wielski, 2016-03-03
@photosho

Greedy loading.
In the model something like:

public function commentsCount()
    {
      return $this->comments()
        ->selectRaw('count(id) as aggregate')
        ->groupBy('id');
    }
    public function getCommentsCountAttribute()
    {
      if ( ! array_key_exists('commentsCount', $this->relations))
        $this->load('commentsCount');

      $related = $this->getRelation('commentsCount')->first();

      return ($related) ? (int) $related->aggregate : 0;
    }

Each post will have a "commentsCount" attribute with the number of comments.

S
Stanislav Pochepko, 2016-03-02
@DJZT

Post::with('comments')->get()
You will get only two requests. And use count() on your health

D
Dmitry Kuznetsov, 2016-03-02
@dima9595

I don't know for sure, but try using "Active loading".
Laravel 4: https://laravel.ru/docs/v4/eloquent#active
Laravel 5: https://laravel.ru/docs/v5/eloquent#active

A
Arthur, 2016-03-02
@astralo

Make a compound request. Or first post, then take article id through lists and request for comments

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question