我已经应用了 group by with with created_at column using DB query 但喜欢用 laravel eloquent 来做
输出应该是这样的:-
Array
(
[1] => 2
[2] => 3
[3] => 7
[4] => 4
[5] => 5
[6] => 7
[7] => 2
[8] => 9
[9] => 0
[10] => 4
[11] => 0
[12] => 0
)
请提供任何帮助我做到这一点。
最佳答案
请尝试以下步骤:-
- 运行composer安装包:composer require nesbot/carbon
- 在您的代码之上:使用 Carbon\Carbon;
假设我有模型用户,
$users = User::select('id', 'created_at')
->get()
->groupBy(function($date) {
//return Carbon::parse($date->created_at)->format('Y'); // grouping by years
return Carbon::parse($date->created_at)->format('m'); // grouping by months
});
$usermcount = [];
$userArr = [];
foreach ($users as $key => $value) {
$usermcount[(int)$key] = count($value);
}
for($i = 1; $i <= 12; $i++){
if(!empty($usermcount[$i])){
$userArr[$i] = $usermcount[$i];
}else{
$userArr[$i] = 0;
}
}
希望它能帮助你制作这样的数组。
关于php - 如何在laravel中获取所有月份的记录数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43093289/