首页 > 解决方案 > 在 Laravel 中有多个 groupBy 日期?

问题描述

我怎样才能实现这个输出(下图)。

在此处输入图像描述

这是我的Types Table

在此处输入图像描述

这是我的Accounts Table

在此处输入图像描述

这是我的Type Model

public function accounts()
{
    return $this->hasMany('App\Accounts');
}

这是我的Account Model

public function type()
{
    return $this->belongsTo('App\Type', 'type_id');
}

我想要做的是,我想将accounts tablebytypes和 by分组month,然后我想amount在每个上添加所有month,并使用DataTables.

我试过这段代码,但它没有给出预期的输出。

$query = Accounts::with('type')->whereYear('created_at', $selectedYear)->select('type_id',
    DB::raw('type_id as type_id'), 
    DB::raw('sum(amount) as total_amount'),
    DB::raw("DATE_FORMAT(created_at,'%m') as months")
)->groupBy('months')->get();

我仍然停留在这部分,

提前致谢

标签: laravellaravel-5eloquent

解决方案


Laravel 文档说您可以在 groupBy 方法中传递多个参数。

https://laravel.com/docs/8.x/queries#ordering-grouping-limit-and-offset

$query = Accounts::with('type')->whereYear('created_at', $selectedYear)->select('type_id',
    DB::raw('type_id as type_id'), 
    DB::raw('sum(amount) as total_amount'),
    DB::raw("DATE_FORMAT(created_at,'%m') as months")
)->groupBy('type_id', 'months')->get();

推荐阅读