【发布时间】:2019-07-05 14:48:47
【问题描述】:
我正在处理 Laravel 项目,我需要获取一些数据,对各列求和并将结果分组为 M-y(1 月 19 日)格式以显示在每月条形图中。
我能够成功地对数据进行汇总和分组,但问题是,对于没有任何记录的月份,我仍然希望以总数等于 0 的方式显示在图表中。
这是我目前的做法:
$data = $this->user->income()
->whereBetween('game_date', ['2019-01-01', '2019-04-30'])
->selectRaw('sum(total_score) as score,
sum(total_stars) as stars,
MONTH(game_date) as month,
DATE_FORMAT(game_date,"%b") as month_name
')
->groupBy('month', 'month_name')
->get();
这给了我以下结果(缺少没有任何记录的月份):
[
{
"score": "707",
"stars": "64",
"month": 1,
"month_name": "Jan"
},
{
"score": "200",
"stars": "29",
"month": 3,
"month_name": "Mar"
}
]
并且预期的结果是包括缺少月份以使图表清晰可见:
[
{
"score": "707",
"stars": "64",
"month": 1,
"month_name": "Jan"
},
{
"score": "0",
"stars": "0",
"month": 2,
"month_name": "Feb"
},
{
"score": "200",
"stars": "29",
"month": 3,
"month_name": "Mar"
},
]
请注意,->whereBetween('game_date', []) 将离开的日期从月初到月底(涵盖完整的月度记录)。
【问题讨论】:
标签: laravel eloquent laravel-5.6 laravel-collection