1

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.

MacroMan
  • 2,335
  • 1
  • 27
  • 36

1 Answers1

6

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.

philwinkle
  • 7,036
  • 3
  • 27
  • 46
  • If you know how database works you dont need spend process to load all category to seach parent, and load parent to search other parent, how many loops and load you want do? – Guerra Sep 11 '12 at 16:52
  • 4
    firstly - Don't downvote because an answer disagrees with your own - it's bad form. Second - using the method I describe does not load anything but the required category - not all categories and necessitating a loop. Are you new to Magento?? Using Models allows Magento to cache results and reuse in the same run of an instance. A raw query hits the db every time. Using the API is standard Magento practice - avoid raw SQL. http://stackoverflow.com/a/9823256/582138 – philwinkle Sep 11 '12 at 16:57