对于图表 API,我需要提供每天的注册用户数。
//fetch all created_at dates of users from the last week
$signUpsLastWeek = User::whereDate('created_at', '>=', now()->subDays(7))->select('created_at')->get();
//group them now by date now, using collection operations
dd($signUpsLastWeek->groupBy(function($item) {
return $item->created_at->format('m.d');
}));
//now manipulate the collection a bit, so we get the date with the amount of new registered users
$signUpsLastWeek->mapWithKeys(function ($userGroup, $key) {
return [$key => $userGroup->count()];
})
回报:
Illuminate\Database\Eloquent\Collection {#774 ▼
#items: array:1 [▼
"01.19" => 4
]
}
这工作正常,留下一个问题。
在上面的示例代码中,其他日期有 0 个新注册,这意味着该集合应类似于:
Illuminate\Database\Eloquent\Collection {#774 ▼
#items: array:1 [▼
"01.25" => 0,
"01.24" => 0,
"01.23" => 0,
"01.22" => 0,
"01.20" => 0,
"01.19" => 4,
...,
]
}
知道如何也包括 0 金额吗?