gpt4 book ai didi

php - 如何在laravel中获取所有月份的记录数

转载 作者:行者123 更新时间:2023-11-29 04:05:41 25 4
gpt4 key购买 nike

我已经应用了 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
)

请提供任何帮助我做到这一点。

最佳答案

请尝试以下步骤:-

  1. 运行composer安装包:composer require nesbot/carbon
  2. 在您的代码之上:使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com