Using CakePHP 1.2, I am trying produce a GROUP BY
query:
SELECT `categories`.*, COUNT(`entities`.id)
FROM `categories`
LEFT JOIN `entities` ON (`categories`.`id` = `entities`.`category_id`)
GROUP BY `categories`.`id`
How would/should I go about doing this? I am using 'Containable' if that helps.
This is what I eneded up with:
$options = array(
'conditions' => $conditions,
'fields'=>array('Category.*','COUNT(`Entity`.`id`) as `entity_count`'),
'joins' => array('LEFT JOIN `entities` AS Entity ON `Entity`.`category_id` = `Category`.`id`'),
'group' => '`Category`.`id`',
'contain' => array('Domain' => array('fields' => array('title')))
);
return $this->find('all', $options);
Model->find() has a group
param.
Possible keys by default, all of which are optional:
$params =
array(
'conditions' => array('Model.field' => $thisValue), //array of conditions
'recursive' => 1, //int
//array of field names
'fields' => array('Model.field1', 'DISTINCT Model.field2'),
//string or array defining order
'order' => array('Model.created', 'Model.field3 DESC'),
'group' => array('Model.field'), //fields to GROUP BY
'joins' => array('Join relations here'), // for ex: LEFT JOIN `entities` AS Entity ON `Entity`.`category_id` = `Category`.`id`
'limit' => n, //int
'page' => n, //int
'offset' => n, //int
'callbacks' => true //other possible values are false, 'before', 'after'
);
Query:
$resp = find('all', $params);
debug($resp);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With