简体   繁体   中英

Magento - How to check if a category is a child of another

I am retrieving all category IDs that a product belongs to like so in a helper:

$productCategories = $this->getProduct()->getCategoryIds();

This gives me an array of category IDs. In my case, each product will only be in one sub-category. From the IDs I need to figure out the logical order based on which categories are children of which.

The aim is to create a method which I can call and specify the level of category I want for a product and it will return the path to that category.

I know I can load a category like so:

Mage::getModel('catalog/category')->load($categoryId)

and I know what I'm doing in PHP, but just a little stuck on the logic (and methods) to use here to achieve what I want.

The easiest way is to test if it has a Parent Id associated to it. A parent_id that is > 0 means that it is a lower-level category. If the parent_id equals one it means that it is one level lower than the root category.

$category = Mage::getModel('catalog/category')->load($categoryId)
echo $category->getParentId();

I advise against using raw SQL as it is bad practice, the database schema may at some point change.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM