Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CakePHP and GROUP BY

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.

like image 944
Lizard Avatar asked May 28 '10 14:05

Lizard


3 Answers

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);
like image 95
Lizard Avatar answered Oct 20 '22 19:10

Lizard


Model->find() has a group param.

like image 8
webbiedave Avatar answered Oct 20 '22 20:10

webbiedave


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);
like image 4
Aditya P Bhatt Avatar answered Oct 20 '22 20:10

Aditya P Bhatt