我有一个方法,获取一个月参数,从users表中选择该月的行。我想显示一个月的注册用户数。
public function registeredUsersDaily($month)
{
$countOfDailyRegisteredUsersForAMonth = User::user()
->where(DB::raw('created_at'), '=', $month)
->groupBy('date')
->orderBy('date')
->get([
DB::raw('DATE(created_at) as date'),
DB::raw('COUNT(*) as count')
]);
dd($countOfDailyRegisteredUsersForAMonth);
}
它仅返回用户表中存在的日期的计数,因此我希望对于不存在的日期为零。
|date|count|
| 5 | 10 |
| 15 | 3 |
我希望得到这样的结果:
|date |count |
| 1 | 0 |
| 2 | 0 |
| 3 | 0 |
| 4 | 0 |
| 5 | 10 |
| 6 | 0 |
| 7 | 0 |
| 8 | 0 |
| 9 | 0 |
| 10 | 0 |
| 11 | 0 |
| 12 | 0 |
| 13 | 0 |
| 14 | 0 |
| 15 | 3 |
....
请查看这样的
$dateValues = array_column($countOfDailyRegisteredUsersForAMonth, "date");
$maxDate = max($dateValues);
$likeYouWant=[];
for ($i = 1; $i <= $maxDate; $i++)
{
$likeYouWant[] = ["date" => $i, "count" => in_array($i, $dateValues) ? $countOfDailyRegisteredUsersForAMonth[array_search($i, $dateValues)]["count"] : 0];
}
print_r($likeYouWant);
如果您想要在该migration
文件中提及的默认日期,或者您也可以在model
中执行此操作,此时您可以在没有用户指定日期的情况下检索数据。您也可以参考此处了解更多信息
How to pass default values to controller by routing in Laravel 5?
从我从评论中得到的结论:我认为这里最好的事情是计算每月每天创建的用户数量。如果没有人在指定日期注册,这将使您获得零。有了这个,您可能会遍历日期,检查每个日期注册的用户总数。
例如,让我们尝试从现在起30天内创建用户:
$results = [];
$startOfDay = now()->createMidnightDate();
for($i=0; $i<=30; $i++)
{
$total_count = User::whereBetween('created_at', [$startOfDay->subDays($i-1), $startOfDay->subDays($i)])
->count();
array_push($results[ $startOfDay->subDays($i)->format('d')], $total_count);
}
有了这个,我想你现在可以使用数组的结果了。