CakePHP and GROUP BY

2020-08-13 01:58发布

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.

3条回答
姐就是有狂的资本
2楼-- · 2020-08-13 02:22

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);
查看更多
Summer. ? 凉城
3楼-- · 2020-08-13 02:28

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);
查看更多
我命由我不由天
4楼-- · 2020-08-13 02:31

Model->find() has a group param.

查看更多
登录 后发表回答