我正在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', [])
的离开日期为月初和月末(包含完整的月度记录)。