在laravel模型中按字段统计记录

在laravel模型中按字段统计记录,laravel,eloquent,Laravel,Eloquent,我正在寻找获取和数组的最佳方法,该数组按某个字段对某个有说服力的模型的现有行进行计数。Guest—具有类型字段的安装模型。现在我用这种方法来做 $typeCount = Installation::select('type', DB::raw('COUNT(*) as count')) ->groupBy('type') ->get() ->mapWithKeys(function($item) { return [$item['type'] =&g

我正在寻找获取和数组的最佳方法,该数组按某个字段对某个有说服力的模型的现有行进行计数。Guest—具有类型字段的安装模型。现在我用这种方法来做

$typeCount = Installation::select('type', DB::raw('COUNT(*) as count'))
  ->groupBy('type')
  ->get()
  ->mapWithKeys(function($item) {
        return [$item['type'] => $item['count']];
  })->toArray();
$typeCount将返回如下数组

[
     "contrib" => 2,
     "official" => 1,
]
是否有更好的方法或优雅的方法???

根据方法:

集合提取(字符串$column,字符串| null$key=null)

Laravel将使用第二个参数的列值作为键,使用第一个参数的列值作为值

$typeCount=Installation::select('type',DB::raw('COUNT(*)as COUNT'))
->groupBy('type')
->拔毛('计数','类型')
->toArray();
根据方法:

集合提取(字符串$column,字符串| null$key=null)

Laravel将使用第二个参数的列值作为键,使用第一个参数的列值作为值

$typeCount=Installation::select('type',DB::raw('COUNT(*)as COUNT'))
->groupBy('type')
->拔毛('计数','类型')
->toArray();