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

后端 未结 5 916
无人共我
无人共我 2020-12-11 08:39

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-cat

5条回答
  •  余生分开走
    2020-12-11 09:39

    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.

提交回复
热议问题