Laravel 计数多级 groupBy

标签 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, 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/

相关文章:

php - Laravel 查询生成器上的子查询 Where 条件

MySQL 分组与求和

swift - 在 UILabel 中显示 tableView 计数

r - 计算 R 中数据框列中的不同值

php - 如何返回 table1 中不存在于 laravel 的 table2 中的行

php - array_key_exists() 错误/编辑供应商文件

php - Laravel5.2 Session 使用 forget() 但没有工作

python - Pandas GroupBy计算满足一定条件的加权百分比

r - 在 R 中逐个折叠数据

Mysql函数从过程调用返回行数