如何计算 Laravel 中分组集合中的项目数?

How do I count the number of Items in a grouped collection in Laravel?

我想计算每个分组集合中的项目数。假设集合 returns 三组项目,我想计算每组中的集合

我这样做了,但对我来说效果不佳

$collection = Vendor::all();
$grouped = $collection->groupBy('vendor_discount');
$counted = $grouped->countBy();
return $counted->all();

这是我返回的错误

array_key_exists(): The first argument should be either a string or an integer

通过这样做

$user_info = DB::table('vendors')
                 ->select('vendor_discount', DB::raw('count(*) as total'))
                 ->groupBy('vendor_discount')
                 ->get();

这是结果

0: {vendor_discount: null, total: 1}
total: 1
vendor_discount: null
1: {vendor_discount: "10%", total: 2}
total: 2
vendor_discount: "10%"
2: {vendor_discount: "20%", total: 2}
total: 2
vendor_discount: "20%"

如何在视图模板中正确显示?

您的查询

$user_info = DB::table('vendors')
                 ->select('vendor_discount', DB::raw('count(*) as total'))
                 ->groupBy('vendor_discount')
                 ->get()->toArray();

return $user_info;

然后在查看文件

//Loop through the values
foreach($user_info as $user){
    echo $user->vendor_discount." - ".$user->total;
}