【问题标题】:How do I get product category information using collections in Magento如何使用 Magento 中的集合获取产品类别信息
【发布时间】:2010-03-16 13:17:11
【问题描述】:

我正在尝试从我们的 Magento 商店输出所有产品 - 以下代码有效,但我还需要获取类别 ID 和父类别名称。谁能建议我如何做到这一点?

$product = Mage::getModel('catalog/product'); 
$productCollection = $product->getCollection()
->addAttributeToSelect('*');


foreach ( $productCollection as $_product ) {
    echo $_product->getName().'<br/>';        
}

【问题讨论】:

    标签: collections magento


    【解决方案1】:

    在某些情况下 $_product->getCategory() 可能返回空并导致错误。

    更好的解决方案是按 ID 获取类别:

    $categoryIds = $_product->getCategoryIds();
    
    foreach($categoryIds as $categoryId) {
        $category = Mage::getModel('catalog/category')->load($categoryId);
        echo $category->getName();
        echo $category->getUrlPath();
     }
    

    【讨论】:

      【解决方案2】:

      由于产品可以分配到多个类别,我认为您的概念可能有点偏离,除非您为每个类别加载一个集合。如果给定产品有多个类别,您预计会看到什么?

      无论如何,在类别页面中,您都可以使用以下内容:

      $currentCat = $_product->getCategory();
      

      要获取该产品所属的所有类别:

      $categories = $_product->getCategoryCollection();
      foreach($categories as $_category) {
          // do something
      }
      

      希望对您有所帮助。谢谢,

      【讨论】:

      • 感谢乔! Magento 是一种我现在不是超级粉丝的野兽! :-)
      猜你喜欢
      • 1970-01-01
      • 2015-04-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-27
      • 2017-04-05
      • 2014-09-02
      • 1970-01-01
      相关资源
      最近更新 更多