【问题标题】:Magento How to get The Parent Category of A Sub-Category from A ProductMagento 如何从产品中获取子类别的父类别
【发布时间】:2012-02-22 09:04:58
【问题描述】:
Root Category (id: 1)
 - Apparel (id: 2)
   -- Shirts (id:4)
   -- Pants  (id:5)
 - Accessories (id: 3)
   -- Handbags (id:6)
   -- Jewelry (id:7)

在 Magento 上,我们可以使用 $productObj->getCategoryIds() 获取产品的类别 ID

$productObj = Mage::getModel('catalog/product')->load($product_id);
$categoryIds =  $productObj->getCategoryIds();

这将返回产品的类别 ID 数组。我特别需要获得产品类别的第一级父级。以上面的分类树为例,如果一个产品被归类在 Pants 分类中,我想得到第一级分类 Apparel(在这种情况下,只有产品标记在 裤子 类别下,但未标记在 服装 类别下)。

问题:我可以通过什么方法来获取子类别的父类别,或者是否可以从产品中获取第一级类别?

【问题讨论】:

    标签: magento tree parent categories product


    【解决方案1】:

    您可以使用catalog/category模型及其方法getParentCategory()

    foreach ($categoryIds as $iCategoryId) {
        $m = Mage::getModel('catalog/category')
            ->load($iCategoryId)
            ->getParentCategory();
        var_dump($m->debug());
    }
    

    【讨论】:

    • 请原谅我的小编辑。使用debug 比使用getData 更好,因为debug 递归地将包含的对象转换为数组并隐藏它们的私有成员。它还避免了会消耗所有内存的无限循环。
    • @clockworkgeek:没问题。我知道debug(),你是对的。 getData() 东西来自我的 IDE var_dump 宏。多年来无法将其更改为debug()^^ 不再。谢谢^^
    • 我有一个Mage::log() 宏。我想伟大的思想是一样的;)
    猜你喜欢
    • 1970-01-01
    • 2012-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多