2016-01-12 61 views
0

我想在cakephp3中按年份分組。我能夠得到使用 以下方式的數據,但它不是仍在逐年分組如何根據查詢結果中的字段創建分組結構?

$query = $this->Alerts->query(); 
$year = $query->func()->year([ 
    'added_on' => 'literal' 
]); 

$month = $query->func()->monthname(['added_on' => 'literal']); 
$monthAlertsCount = $query->func()->count($month); 
$data = $query 
    ->select([ 
     'year' => $year, 
     'month' => $month, 
     'count' => $monthAlertsCount 
    ]) 
    ->group($year) 
    ->group($month); 

$status = "success"; 
$this->set('response', $status); 
$this->set('year', $data); 
$this->set('_serialize', ['response','year']); 

電流輸出如下(我想要的方式。):

{ 

    "response":"success", 
    "year":[ 
     { 
      "year":"2013", 
      "month":"November", 
      "count":"1" 
     }, 
     { 
      "year":"2014", 
      "month":"February", 
      "count":"2" 
     }, 
     { 
      "year":"2014", 
      "month":"January", 
      "count":"3" 
     }, 
     { 
      "year":"2015", 
      "month":"December", 
      "count":"6" 
     }, 
     { 
      "year":"2015", 
      "month":"February", 
      "count":"3" 
     }, 
     { 
      "year":"2015", 
      "month":"January", 
      "count":"4" 
     }, 
     { 
      "year":"2016", 
      "month":"January", 
      "count":"83" 
     } 
    ] 

} 

預期輸出:

{ 

    "response":"success", 
    "year":[ 
     { 
      "2013":[ 
       { 
        "month":"November", 
        "count":"1" 
       } 
      ], 
      "2014":[ 
       { 
        "month":"February", 
        "count":"2" 
       }, 
       { 
        "month":"January", 
        "count":"3" 
       } 
      ], 
      "2015":[ 
       { 
        "month":"December", 
        "count":"6" 
       }, 
       { 
        "month":"February", 
        "count":"3" 
       }, 
       { 
        "month":"January", 
        "count":"4" 
       } 
      ], 
      "2016":[ 
       { 
        "month":"January", 
        "count":"83" 
       } 
      ] 
     } 
    ] 

} 

任何人都可以幫我在cakephp3中獲得預期的輸出嗎?

回答

0

使用收集方法groupBy() - 記住,查詢是集合對象(種類)!

$data = $query 
    ->select([ 
     'year' => $year, 
     'month' => $month, 
     'count' => $monthAlertsCount 
    ]) 
    ->group($year) 
    ->group($month) 
    ->groupBy('year'); 

這將創建所需的分組結構,但它不會從各行,如果你想移除這些刪除year領域,使用映射器,像

// ... 
->groupBy('year') 
->map(function ($rows) { 
    foreach ($rows as &$row) { 
     unset($row['year']); 
    } 
    return $rows; 
}); 

也見

+0

斐伊川,感謝您的回覆,這幾乎接近我想要的,但我不是仍然能夠除去年 - > GROUPBY( '年') - > map(函數($ row)){$ row ['year']); return $ row; }); 不會從輸出中刪除年份 –

+0

@AkshayMalhotra忘記了映射器不會遍歷組...檢查更新的代碼示例。 – ndm

+0

萬分感謝你!有效。 –