Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Magento - get a parent category and all sub-sub-categories

I have a single category, that has 2 subcategories. Within each of these categories, are 5 subcategories.

Is there a way to get a list of all of these 10 sub-sub-categories?

Thanks

EDIT:

Something like this:

  Main Category
       Sub_Cat_1
            Cat_1
            Cat_2
            Cat_3
       Sub_Cat_2
            Cat_4
            Cat_5
            Cat_6

  Wanting output like:

  Cat_1
  Cat_2
  Cat_3
  Cat_4
  Cat_5
  Cat_6

Thanks

like image 546
terrid25 Avatar asked Nov 30 '22 17:11

terrid25


2 Answers

All answers so far load children categories in a loop which is generally bad practice and causes execution of many SQL queries where a single one would suffice.

Performant Single Query Solution:

Let $parentCategory be your Main Category, then this collection will load all subcategories, two levels below:

$subcategoryCollection = Mage::getModel('catalog/category')
    ->getCollection()
    ->addFieldToFilter('level', $parentCategory->getLevel() + 2)
    ->addFieldToFilter('path', ['like' => $parentCategory->getData('path') . '/%']);

The path field contains the category id prefixed with all ancestor ids in the form 1/2/3. Database wise it is a column in catalog_category_entity that has an index, so comparison like this has no performance issues.

like image 52
Fabian Schmengler Avatar answered Dec 05 '22 21:12

Fabian Schmengler


Figured it out:

$cat = Mage::getModel('catalog/category')->load(24);
$subcats = $cat->getChildren();

foreach(explode(',',$subcats) as $subCatid)
{
  $_category = Mage::getModel('catalog/category')->load($subCatid);
  if($_category->getIsActive()) {
    $sub_cat = Mage::getModel('catalog/category')->load($_category->getId());
    $sub_subcats = $sub_cat->getChildren();
    foreach(explode(',',$sub_subcats) as $sub_subCatid)
    {
          $_sub_category = Mage::getModel('catalog/category')->load($sub_subCatid);
          if($_sub_category->getIsActive()) {
              echo '<li class="sub_cat"><a href="'.$_sub_category->getURL().'" title="View the products for the "'.$_sub_category->getName().'" category">'.$_sub_category->getName().'</a></li>';
          }
     }
  }
}

Thanks for looking!

like image 22
terrid25 Avatar answered Dec 05 '22 20:12

terrid25