I\'m trying to group by date of birth and count based on the results, using CakePHP. Here\'s my query.
$data = $this->User->find(\'all\', array(
\
The results you get are pretty much the best that CakePHP produces.
To simplify this you should use Set::combine which re-indexes your array.
You would need to call $data = Set::combine($data, '{n}.0.age', '{n}.0.COUNT(id)');
This would return an array with age as the index and count as the value:
Array
(
[9] => Array
(
[COUNT(id)] => 1
)
[10] => Array
(
[COUNT(id)] => 1
)
...
)
The reason for the extra depth in the array is that cake uses the model as the key for the inner array if you are not using calculated fields, so that you can put in multiple models as fields and they will be split into different arrays. When you use calculated fields it keeps the same structure, but doesn't know the model so has to put it in a general array.
So lets say you want to group by male/female as well and you have a User.sex field, which is not a calculated field.
$data = $this->User->find('all', array(
'fields' => array(
"User.sex"
"DATE_FORMAT(NOW(), '%Y') - DATE_FORMAT(User.dob, '%Y') - (DATE_FORMAT(NOW(), '00-%m-%d') < DATE_FORMAT(User.dob, '00-%m-%d')) AS age",
'COUNT(User.id) AS [count]' // n.b. you have to give aliases normally
),
'group' => 'age', 'User.sex'
));
This would return (something like):
Array
(
[0] => Array
(
[User] => Array
(
[sex] => Male
)
[0] => Array
(
[age] => 4
[count] => 1
)
)
[1] => Array
(
[User] => Array
(
[sex] => Female
)
[0] => Array
(
[age] => 10
[count] => 1
)
)
[2] => Array
(
[User] => Array
(
[sex] => Male
)
[0] => Array
(
[age] => 10
[count] => 1
)
)
)
Thus for consistency the extra depth is always there even if you only use calculated fields