开发者

CakePHP and GROUP BY

开发者 https://www.devze.com 2023-01-01 04:27 出处:网络
Using CakePHP 1.2, I am trying produce a GROUP BY query: SELECT `categories`.*, COUNT(`en开发者_如何学JAVAtities`.id)

Using CakePHP 1.2, I am trying produce a GROUP BY query:

SELECT `categories`.*, COUNT(`en开发者_如何学JAVAtities`.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);
0

精彩评论

暂无评论...
验证码 换一张
取 消