表格项目:
[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('types')->get(['created_at', 'type'])
->groupBy(fn ($item) => Carbon::parse($item->created_at)->format('Y-m-d'))
->map(function ($item, $key) {
$details = $item->map(fn ($type) => $type->type)
->unique()->map(fn ($i) => ['type'.$i => $item->sum(fn ($type) => $i === $type->type ? 1 : 0)]);
return ['date' => $key, 'amount' => $item->count(), 'details' => $details];
});
关于Laravel 计数多级 groupBy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63383806/