Category Collection – Programmatically Get Subcategories of Root Categories

categorycollection-filteringcollection;

I am working on a collection query of categories:

$categories_check = Mage::getModel('catalog/category')
    ->getCollection()               
    ->setStoreId($storeId)           
    ->addFieldToFilter('is_active', 1)       
    ->addAttributeToFilter('path', array('like' => "1/{$rootCategoryId}/%"))   
    ->setProductStoreId($storeId)   
    ->setLoadProductCount(1)   
    ->addAttributeToSelect('*');

It returns the categories below root category $rootCategoryId. My requirement is to change this query, that it works for an array of root categories.

Like when I pass the array $rootcat = array('15,20,25,35'); it provides me categories below these root categories.

Best Answer

Edited:

As basic of on your last question Programatically get category collection by multiple root category id .I have give you the answer.

Have create multiple OR condition for addFieldToFilter() for getting the result on basic of path field

You should this script which may be give u your required result.

require_once "YOurMagentoDirapp/Mage.php";
umask(0);
ini_set('display_errors', 1);
Mage::app("admin");


$buildArray=array();

$rootId = Mage_Catalog_Model_Category::TREE_ROOT_ID;
$rootids= array(12,15,18,20);

foreach($rootid as $id){

  $buildArray[]= array('attribute' =>'path','like'=>$rootId.'/'.$id.'/%');

}

$collection = Mage::getModel('catalog/category')->getCollection()
        ->addFieldToFilter('is_active',1)
->addFieldToFilter($buildArray);

For getting the query of a collection.You can try this.

$CollectionObject->getSelect()->__toString();

For you case. use below

echo $categories_check->getSelect()->__toString();

Donot use

  • ->setStoreId($storeId)
  • ->setProductStoreId($storeId)

  • ->setLoadProductCount(1)