Answer the question
In order to leave comments, you need to log in
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 foreach
for 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
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;
}
Post::with('comments')->get()
You will get only two requests. And use count() on your health
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
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question