我想在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 :(得分: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;
});
另见