gpt4 book ai didi

Laravel 计数多级 groupBy

转载 作者:行者123 更新时间:2023-12-04 09:09:33 24 4
gpt4 key购买 nike

项目 :

[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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com