获取产品的父类别,即使直接访问该产品也是如此 [英] Get a product's parent category even if it is accessed directly

查看:39
本文介绍了获取产品的父类别,即使直接访问该产品也是如此的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义模型/块,可以获取当前产品的父类别:

I have a custom model/block that gets the current product's parent category:

class Namespace_Module_Model_Product extends Mage_Catalog_Model_Product
{
    public function someFunction()
    {
        $category = $this->getCategory();
        ...
    }
}

此自定义块在产品页面上使用.如果通过其父类别(例如:domain.com/some-category/my-product.html)访问该产品,则此方法非常适用.但是,如果直接访问该产品(例如通过搜索),并且URL类似于domain.com/my-product.html,则该产品不起作用. Mage_Catalog_Model_Product中所有可用于检索类别的函数都将返回空值,就像未将产品分配给任何类别一样.

This custom block is used on a product's page. This works perfectly if the product is accessed via its parent category, e.g.: domain.com/some-category/my-product.html. However, if the product is accessed directly (for example through the search) and the URL is like domain.com/my-product.html, it doesn't work. All functions from Mage_Catalog_Model_Product that could be used to retrieve the category return empty values, as if the product wasn't assigned to any categories.

我的问题是:即使未通过产品类别访问产品,该产品类别的全局检索方式又是什么?

My question is: What is the global way to retrieve a product's category, even if that product is not accessed via its category?

推荐答案

第一步:稍微调整您的期望-Magento中的产品不仅限于一个类别.因此,检索产品类别的全局方法"应该是检索产品所属的任何类别的列表的全局方法".

First step: Adjust your expectation slightly — a product in Magento isn't limited to a single category. Therefore, "a global way to retrieve a product's category" should be "a global way to retrieve a list of any categories the product is in".

您需要

  1. 获取对产品对象的引用

  1. Get a reference to a product object

使用该产品对象获取类别集合

Use that product object to get a category collection

遍历集合并提取所需的类别信息

Run through the collection and pull out the category information you want

如果您在产品页面上,则可以从注册表中获取当前产品.

If you're on the product page, you can grab the current product from the registry.

$product = Mage::registry('product');

然后使用

$c       = $product->getCategoryCollection()
->addAttributeToSelect('*');

addAttributeToSelect方法可确保您获取所需的所有字段.

The addAttributeToSelect method ensures you get all the fields you need.

最后,您可以自己获得各个类别

Finally, you can get the individual categories themselves with

foreach($c as $category)
{
    var_dump($category->getData());
    var_dump($category->getName());
}

您还可以通过以下方式获取第一类

You could also grab the first category with

$category = $c->getFirstItem();
var_dump($category->getData());
var_dump($category->getName());

这篇关于获取产品的父类别,即使直接访问该产品也是如此的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆