GroupBy inside withCount closure (Laravel 5.3.26)

In Laravel 5.3.26, is it possible to group a withCount result based on a column of this relationship? Something like the following:

 $brands = \App\Models\Brand::withCount([ 'products' => function ($query) { $query->groupBy('extra_attribute'); } ]) ->get(); 

This piece of code returns an empty collection.

Maybe I just don’t look at the right places in the documentation or I don’t look right, but I can’t find anything about this particular scenario.

Can someone point me in the right direction?

Thanks a bunch!


Edit: Currently, I seem to have solved this:

 $brands = \App\Models\Brand::with([ 'products' => function ($query) { $query->select('brand_id', 'extra_attribute') ->selectRaw('COUNT(*) AS products_count') ->groupBy('extra_attribute'); } ]); 

and the ability to get the final value through something like $brand->products->sum('products_count') .

Feels extremely dirty and probably is. Is this really the only way?

+5
source share
1 answer

groupBy() should not be used in withCount() , since withCount() is going to load an account of all elements of the products collection for each Brand , grouped by Brand in the returned collection. This would be equivalent to $brand->products->count() on one Brand .

Between the two examples, groupBy() not required unless you are using this data elsewhere. If so, then it might be better to access your totals in collections as:

 //Controller $brands = \App\Models\Brand::with('products')->get(); //View @foreach($brands as $brand) <div>TOTAL PRODUCTS: {{ $brand->products->count() }}</div> @foreach($brand->products->groupBy('extra_attribute') as $attribute => $products) <div>TOTAL {{ $attribute }}: {{ $products->count() }}</div> @endforeach @endforeach 

- OR -

You can have the best of both worlds and attach an account and a grouped relationship by simply doing both:

 $brands = \App\Models\Brand::withCount('products') ->with(['products' => function ($query) { return $query->groupBy('extra_attribute'); }])->get(); 

Then you can access the products_count brand and grouped products:

 $brands->each(function($brand) { $brand->products_count; $brand->products->each(function($products, $extra_attribute) { // Grouped Products }); }); 
0
source

Source: https://habr.com/ru/post/1261665/


All Articles