Mehic.info

CakePhp – How to fetch root categories with childs associated

Very simple :

/**
* Get categories with childs by parent id
* @return array
*/
public function getRootCategoriesHaveChilds(){

$conditions = array('Category.parent_id ' => 0);
$fields = array('Category.*','(SELECT COUNT( cat2.id ) FROM categories AS cat2 WHERE cat2.parent_id = Category.id) as Total' );
$group = array('Category.id HAVING Total>0');
return $this->find('all', array('conditions'=>$conditions, 'fields'=>$fields, 'group' => $group, 'recursive' =>-1));
}

Note : Root categories don’t have parent (parent_id = 0)