2017-03-29 1 views
0

내가 DB 쿼리를 사용 created_at 컬럼에 의해 그룹을 신청 한 모든 개월 레코드 수를 얻을 수 있지만, 다음과 같이해야한다 웅변 laravel에 의해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 
) 

이 일을 도와주세요. 이

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

같은

+0

[Laravel Eloquent]의 가능한 복제본은 일별 그룹화됩니다. (http://stackoverflow.com/questions/20603075/laravel-eloquent-get-results-grouped-by-days) – apokryfos

답변

1

아래 단계를 시도해보십시오 : -

  1. 패키지를 설치할 작곡가를 실행하십시오. 작곡가는 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;  
        } 
    } 
    

한다고 가정 내가 모델 사용자를 가지고, 그것은 같은 배열을하는 데 도움이됩니다 바랍니다.

+0

와우 이스마엘은 laravel eloquent와 같은 것을 찾고있었습니다. 고마워요! –

+0

가장 환영합니다 :) –

0

당신의 created_at 열이 DATETIME 경우, 당신이 할 수있는 그룹은 또한 사전에 월을 선택할 수 있습니다

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