简体   繁体   English

如何获得产品类别?

[英]How to get a Product's Category?

New to PHP so I apologise for the apparent simplicity of this problem. PHP的新手,因此为这个问题的简单性表示歉意。

I understand that you can get a product's categories by doing this: 我了解您可以通过执行以下操作来获得产品的类别:

//load the product
$product = Mage::getModel('catalog/product')->load($productId);

//load the categories of this product 
$categoryCollection = $product->getCategoryCollection();

But how to do I get just the first product of the category? 但是,如何获得该类别的第一个产品?

The getCategoryCollectionn function returns a Magento collection containing all of the product's categories. getCategoryCollectionn函数返回一个包含所有产品类别的Magento集合。 The items in the category collection are Magento category objects, and a category has a method ( getProductsCollection ) that returns a collection containing all of the products in the category. 类别集合中的项目是Magento类别对象,并且类别具有方法( getProductsCollection ),该方法返回包含该类别中所有产品的集合。 Magento collections have a fairly rich API that can be used to fetch specific items from the collection, in this case we want getFirstItem() . Magento集合具有相当丰富的API,可用于从集合中获取特定项目,在这种情况下,我们需要getFirstItem() To put that all together: 放在一起:

$product = Mage::getModel('catalog/product')->load($productId);
$categoryCollection = $product->getCategoryCollection();
foreach ($categoryCollection as $category) {
    $products = $category->getProductsCollection();

    // Here we have the first product
    $firstProduct = $products->getFirstItem();
}

If all you want is the first product in the first category for you current product, you could avoid the loop and do this instead: 如果您想要的只是您当前产品的第一类中的第一个产品,则可以避免循环并改为执行以下操作:

$product = Mage::getModel('catalog/product')->load($productId);
$categoryCollection = $product->getCategoryCollection();
$category = $categoryCollection()->getFirstItem();
$products = $category->getProductsCollection();

// Here we have the first product
$firstProduct = $products->getFirstItem();

Note: Neigher of these code samples are particularly efficient, but without knowing exactly what you're trying to do, I can't propose a more efficient solution. 注意:这些代码示例的邻居特别有效,但是在不完全知道您要做什么的情况下,我无法提出更有效的解决方案。

$product = Mage::getModel('catalog/product')->load($productId);

$cats = $product->getCategoryIds();
foreach ($cats as $category_id) {
    $_cat = Mage::getModel('catalog/category')->load($category_id) ;
    echo $_cat->getName();
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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