【问题标题】:How do I count the number of Items in a grouped collection in Laravel?如何计算 Laravel 中分组集合中的项目数?
【发布时间】:2021-01-30 05:08:49
【问题描述】:

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

我这样做了,但它不适合我

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

这是返回的错误

array_key_exists(): 第一个参数应该是字符串或者整数

这样做

$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%"

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

【问题讨论】:

  • 嘿,它可以工作,但我发现很难在视图模板中显示
  • 你能显示查询后得到的输出吗?
  • 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%"
  • 请问它可读吗?

标签: laravel eloquent laravel-query-builder


【解决方案1】:

您的查询

$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;
}

【讨论】:

  • 它有效..也能够在 Vue 模板中显示..非常感谢
猜你喜欢
  • 2011-08-07
  • 1970-01-01
  • 1970-01-01
  • 2018-08-15
  • 2021-09-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多