A
A
Andrzej Wielski2016-02-20 19:27:16
Laravel
Andrzej Wielski, 2016-02-20 19:27:16

Does the ->with() construct cause a memory leak in Laravel?

Hello.
There is a request like this:

$products->joinRelations('categories')->with('products')->whereNotNull('category_id')->groupBy('category_id')->getCache(['product_categories.*']);

The results of his work are as follows:
87f48c7d76fa410ba060f407b2f35a7b.png
Accordingly, without the ->with('products')
e2e33ffb95794b2aa42ae256cedd11ae.png
construct, the memory consumption is obviously less (but still in excess), but there are more requests (because a new request is executed with each output of products).
Need advice on how best to optimize this business?
I do not ask for ready-made code, please push in the right direction.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrzej Wielski, 2016-02-20
@wielski

Rewrote it like this:

public function scopeGetCategories($query){
      $categories = clone $query;
      return $categories->joinRelations('categories')
            ->selectRaw('*, count(`product_category_values`.`product_id`) as products_count')
            ->whereNotNull('category_id')->groupBy('category_id')
            ->getCache(['product_categories.*']);
    }

To determine the number of products in a category, I used selectRaw .
Accordingly, instead of counting links, I immediately take the value of products_count.
The result, as they say, on the face. Memory consumption is within the normal range.
5f9cb85d591641fd934c318dd0708e6d.png

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question