2010-05-28 29 views
13

con CakePHP 1.2, estoy tratando de producir una consulta GROUP BY:CakePHP y GROUP BY

SELECT `categories`.*, COUNT(`entities`.id) 
FROM `categories` 
LEFT JOIN `entities` ON (`categories`.`id` = `entities`.`category_id`) 
GROUP BY `categories`.`id` 

¿Cómo/debo ir haciendo esto? Estoy usando 'Containable' si eso ayuda.

+0

Puede darnos su Modelos y sus relaciones por favor? Como esto ayudará a saber qué modelos preceden y se siguen uno al otro en su 'find()' –

Respuesta

25

Esto es lo que eneded con:

$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); 
+0

¡No conocía el param del 'grupo', aplausos! – Nicolas

+2

De nada. – webbiedave

5

claves posibles por defecto, todos los cuales son opcionales:

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

Consulta:

$resp = find('all', $params); 

debug($resp);