laravel - 在 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 table
bytypes
和 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();
我仍然停留在这部分,
提前致谢
解决方案
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();
推荐阅读
- .net - ServiceStack BasicAuth 返回 401 和 client_credentials
- xml - 更改微调器颜色箭头
- arrays - 查询数组
在蜂巢中 - java - 使 oracle last_day 函数在 oracle 和 h2 之间兼容
- javascript - 在 Gatsby 中使用根导入插件为 NPM 包创建别名
- php - 在 PHP 中为 json 字符串添加斜杠
- python - YOLO:要么过拟合,要么欠拟合,增加batch还是增加样本图像池?
- java - 使用 forloops 用 json 对象填充 mysql 表
- c++ - 如何使用“get”方法返回类的私有 std::unique_ptr 成员
- sql - 在 LIKE 语句中允许前导零