I am willing to group MySQL results by a column, and also count the records which belong to the same category:
$this->find('all', array(
'fields' => array('UserCheckin.id', 'UserCheckin.capital_id', 'COUNT(UserCheckin.id) as capital_checkins'),
'group' => 'UserCheckin.capital_id'
));
The problem is that capital_checkins is grouped as a separate key in the returned array, whilst I would like it to be under the UserCheckin model. Here’s how the results are returned:
Array
(
[0] => Array
(
[UserCheckin] => Array
(
[id] => 3
[capital_id] => 10
)
[0] => Array
(
[capital_checkins] => 2
)
[Capital] => Array
(
[id] => 10
[name] => London
)
)
[1] => Array
(
...
)
)
Is there a way to include the alias under UserCheckin model?
In cakephp 1.3 you can use virtual field:
in your
UserCheckinmodel:IMPORTANT UPDATE: As @Rob Wilkerson correctly notices, adding a virtual field with aggregate function permanently to your model will [probably] mess up your
findqueries which do not have aGROUP BY(implicitly group all rows in MySQL or just fail with SQL error in SQL Server). Solution is to add a virtual field temporarily at a runtime before query that uses it: