How do i load all the sub categories of a particular Root Category?
I need to form a tree like structure for traversing all the sub categories (including the inactive ones).
Kindly help.
For performance reasons, I would suggest to load all required categories at once, with as few DB queries as possible. Then, simply fetch the children categories as needed from the main collection.
You can achieve this by filtering the path
attribute once you have the according path
value of the parent category.
$rootCatId = 4;
// First query
$category = Mage::getModel('catalog/category')->load($rootCatId);
// Second query
$collection = $category->getCollection()
->addFieldToFilter('path', array('like' => $category->getPath() . '/%'));
Then, build a recursive method to fetch all children as needed from the main collection.
function processChild(Mage_Catalog_Model_Category $category)
{
static $collection;
if (is_null($collection)) {
$collection = $category->getCollection()
->addAttributeToSelect(array('parent_id', 'path'))
->addFieldToFilter('path', array('like' => $category->getPath() . '/%'));
}
// Process the current category, for example echo out the id :)
echo str_pad("{$category->getId()}", $category->getLevel() * 3, ' ', STR_PAD_LEFT) . PHP_EOL;
foreach ($collection->getItemsByColumnValue('parent_id', $category->getId()) as $child) {
processChild($child);
}
}
$rootCatId = Mage::app()->getStore()->getRootCategoryId();
processChild(Mage::getModel('catalog/category')->load($rootCatId));
This is just an example, depending on your use case you will probably modify the code to use a class property instead of a static variable, and use a method instead of a function.
Note that this will only work for categories assigned to the current store, if the flat catalog tables are enabled. If you want to be able to work with arbitrary categories, regardless of the current store, use
Mage::getResourceModel('catalog/category_collection')
instead of $category->getCollection()
to always use the EAV based collection.
And finally, just for completeness sake, a pointer to a core method which gives you the nested categories for the current store:
Mage::helper('catalog/category')->getStoreCategories();
So, If you want to start from the store root categories, you might as well use that method.
To creat a simple one level check you can use the following:
$_rootCatId = 3;
$_rootCategory = Mage::getModel('catalog/category')->load($_rootCatId);
$collection = $_rootCategory->getChildrenCategories();
/* @var $cat Mage_Catalog_Model_Category */
foreach ($collection as $cat) {
echo $cat->getId().' ' .$cat->getName().'<br/>';
}
Here it loads a category and gets each direct child category. At this point you can call $cat->hasChildren()
to check if you can go deeper down the tree of categories and repeat the process for each category.