在Laravel 5.3.26中,是否可以withCount根据该关系的列对结果进行分组?例如:如下:
$brands = \App\Models\Brand::withCount([ 'products' => function ($query) {
$query->groupBy('extra_attribute');
} ])
->get();
Run Code Online (Sandbox Code Playgroud)
这段特殊代码返回一个空集合.
也许我只是没有在文档中查找正确的位置或没有正确搜索,但我找不到任何有关此特定方案的信息.
有人能指出我正确的方向吗?
谢谢你!
编辑:目前我似乎用这个解决了它:
$brands = \App\Models\Brand::with([ 'products' => function ($query) {
$query->select('brand_id', 'extra_attribute')
->selectRaw('COUNT(*) AS products_count')
->groupBy('extra_attribute');
} ]);
Run Code Online (Sandbox Code Playgroud)
并能够通过类似的东西获取总数$brand->products->sum('products_count').
感觉非常脏,可能是.这真的是唯一的方法吗?