获取产品的类别ID和名称

问题描述:

Mage_Catalog_Model_Resource_Eav_Mysql4_Product中有此方法getCategoryIds().此方法返回所请求产品的所有类别ID.我需要修改SELECT语句,以便它也返回类别名称.

There is this method getCategoryIds() in Mage_Catalog_Model_Resource_Eav_Mysql4_Product. This method returns all category IDs of requested product. I need to modify the SELECT statement so it will return also category names.

这是基本查询:


$select = $this->_getReadAdapter()->select()
    ->from($this->_productCategoryTable, 'category_id')
    ->where('product_id=?', $product->getId());

由于某些原因,我不能使用catalog_category_flat表,因此我必须使用EAV表.所以在这一点上,我有这个查询:

I can't use catalog_category_flat table to for some reasons, so I have to use EAV tables. So at this point I have this query:


$select = $this->_getReadAdapter()->select()
    ->from($this->_productCategoryTable, 'category_id')
    ->where('catalog_category_product.product_id=?', $product->getId())
    ->join(
       array('a' =>'catalog_category_entity_varchar'),
       'a.entity_id = catalog_category_product.category_id',
       array('name' => 'value')
    )
    ->join(
       array('b' => $this->getTable('eav/attribute')),
       'b.attribute_id = a.attribute_id',
       array()
    )
    ->where("b.attribut_code = 'name'");

这可行,但是我想问一问是否有更好的方法.

This works, but I'd like to ask if there is a better way of doing it.

最简单,也可能最干净:

Easiest and probably cleanest:

$categories = $product->getCategoryCollection()
    ->addAttributeToSelect('name');

然后您可以遍历集合:

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