如何在laravel中获得所有月份记录

时间:2017-03-29 12:17:21

标签: php mysql laravel-5

我已经使用带有DB查询的created_at列应用group by,但喜欢通过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
)

请提供任何帮助我这样做。

4 个答案:

答案 0 :(得分:4)

请尝试以下步骤: -

  1. 运行composer来安装包:composer require nesbot / carbon
  2. 在您的代码之上:使用Carbon \ Carbon;
  3. 假设我有模型用户,

    $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;    
        }
    }
    

    希望它可以帮助你制作这样的数组。

答案 1 :(得分:0)

如果您的created_at列是DATETIME,则可以将其分组为

Entity::orderBy(...)->groupBy(DB::raw('MONTH(created_at)'))

您也可以提前选择月份

Entity::select(DB::raw('MONTH(created_at) as month')->groupBy('month')->get()->keyBy('month');

答案 2 :(得分:0)

如果要基于不同年份中每个月的计数,请使用以下代码

return $usersPerMonth =User::select(DB::raw('count(id) as `data`'),DB::raw("DATE_FORMAT(created_at, '%Y-%m') new_date"))
        ->groupBy('new_date')->orderBy('new_date')->get();

答案 3 :(得分:0)

修改 Ismael Ansari Post,

 $users = User::select('id', 'created_at')
        ->get()
        ->groupBy(function ($date) {
            return Carbon::parse($date->created_at)->format('m');
        });

    $usermcount = [];
    $userArr = [];

    foreach ($users as $key => $value) {
        $usermcount[(int)$key] = count($value);
    }

    $month = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

    for ($i = 1; $i <= 12; $i++) {
        if (!empty($usermcount[$i])) {
            $userArr[$i]['count'] = $usermcount[$i];
        } else {
            $userArr[$i]['count'] = 0;
        }
        $userArr[$i]['month'] = $month[$i - 1];
    }

    return response()->json(array_values($userArr));

输出:

[
    {
        "count": 1,
        "month": "Jan"
    },
    {
        "count": 0,
        "month": "Feb"
    },
    {
        "count": 0,
        "month": "Mar"
    },
    {
        "count": 0,
        "month": "Apr"
    },
    {
        "count": 0,
        "month": "May"
    },
    {
        "count": 0,
        "month": "Jun"
    },
    {
        "count": 0,
        "month": "Jul"
    },
    {
        "count": 0,
        "month": "Aug"
    },
    {
        "count": 0,
        "month": "Sep"
    },
    {
        "count": 0,
        "month": "Oct"
    },
    {
        "count": 0,
        "month": "Nov"
    },
    {
        "count": 0,
        "month": "Dec"
    }
]