Laravel 拉威尔计数多级分组比
表项目:Laravel 拉威尔计数多级分组比,laravel,group-by,count,multi-level,Laravel,Group By,Count,Multi Level,表项目: [created_at => 2020-08-12 06:00:00, type =>2] [created_at => 2020-08-12 07:00:00, type =>1] [created_at => 2020-08-12 08:00:00, type =>1] [created_at => 2020-08-11 12:00:00, type =>3] [created_at => 2020-08-11 21:00:00
[created_at => 2020-08-12 06:00:00, type =>2]
[created_at => 2020-08-12 07:00:00, type =>1]
[created_at => 2020-08-12 08:00:00, type =>1]
[created_at => 2020-08-11 12:00:00, type =>3]
[created_at => 2020-08-11 21:00:00, type =>3]
我想写一个(Laravel 7)查询,返回如下内容:
[
["date"=>"2020-08-12","amount"=>3, "type1"=>2, "type2"=>1],
["date"=>"2020-08-11", "amount"=>2, "type3"=>2],
]
如何按多层次进行分组和计数?您可以通过一点查询生成器和一点集合来实现这一点:
return DB::table('items')
->selectRaw('DATE_FORMAT(created_at, "%Y-%m-%d") as date, type, COUNT(type) as count')
->groupBy('date', 'type')
->orderBy('date', 'desc')
->get()
->reduce(function ($summary, $item) {
if (! $summary->has($item->date)) {
$summary->put($item->date, collect([
'date' => $item->date,
'amount' => $item->count
]));
} else {
$amount = $summary->get($item->date)['amount'];
$summary->get($item->date)->put('amount', $amount + $item->count);
}
$summary->get($item->date)->put('type'.$item->type, $item->count);
return $summary;
}, collect())
->values()
->toArray();
您可以查看这个包含工作代码的文件数据形状与您想要的不完全相同,但我添加了一些有意义的键,我认为这些键很有用
returndb::table('types')->get(['created_at','type'])
->groupBy(fn($item)=>Carbon::parse($item->created_at)->格式('Y-m-d'))
->映射(函数($item,$key){
$details=$item->map(fn($type)=>$type->type)
->unique()->map(fn($i)=>['type'.$i=>$item->sum(fn($type)=>$i=====$type->type?1:0)];
返回['date'=>$key,'amount'=>$item->count(),'details'=>$details];
});
非常感谢@KurtFriars。不幸的是,“金额”给出了不同“类型”的数量。为了获得不同“类型”计数器的总和,我稍微修改了代码:$summary->put($item->date,collect(['date'=>$item->date,'amount'=>$item->count])
和$summary->get($item->date)->put('amount',amount amount+$item->count
;@thetispro我已经更新了我的答案。如果它对您有效,请接受它:)