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

Dev*_*rma 1 php mysql laravel-5

我已经使用DB查询通过created_at列应用了group by,但是喜欢通过laravel雄辩地做到这一点。

输出应该是这样的:

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
)
Run Code Online (Sandbox Code Playgroud)

请为我提供任何帮助。

小智 6

请尝试以下步骤:

  1. 运行composer安装软件包:composer需要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;    
    }
}
Run Code Online (Sandbox Code Playgroud)

希望它可以帮助您制作类似的数组。