CakePHP and GROUP BY

2020-08-13 02:20发布

问题:

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.

回答1:

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);


回答2:

Model->find() has a group param.



回答3:

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);