How to do GROUP BY HAVING in CakePHP
Before June 2008, there is no clean implementation for GROUP BY. commonly people code with CakePHP will put GROUP BY sintak on conditions, something like this
$this->Product->find(‘all’, array(‘conditions’ => ‘1=1 GROUP BY Product.category_id’));
Now CakePhp have a clean sintak for GROUP BY by new additional paramater on find function. We can use ‘group’ to define GROUP BY on cakephp. For example
$this->Product->find(‘all’, array(‘fields’ => array(‘Product.category_id’, ‘COUNT(Product.hotel_id) as total’), ‘group‘ => array(‘Product.category_id’)));
How if we want to have HAVING sintak on query? i ussually use this solution for new cakephp
$this->Product->find(‘all’, array(‘fields’ => array(‘Product.category_id’, ‘COUNT(Product.hotel_id) as total’), ‘group’ => array(‘Product.category_id HAVING COUNT(Product.hotel_id) > 1′)));