获取产品的类别ID和名称

时间:2011-08-11 11:10:14

标签: magento

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

以下是基本查询:


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

由于某些原因,我无法使用catalog_category_flat表,所以我必须使用EAV表。所以在这一点上我有这个问题:


$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'");

这有效,但我想问一下是否有更好的方法。

2 个答案:

答案 0 :(得分:9)

最容易也可能最干净:

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

然后你可以简单地遍历集合:

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

答案 1 :(得分:0)

我找到了这篇文章:Joining an EAV table并创建了这个函数,它将添加类别连接查询,从集合中使用它。

只需从代码中调用此函数:

// To join the name of category
$this->joinCategoryAttribute('<your table alias>.category_id', 'name');

这就是功能:

public function joinCategoryAttribute($joinOriginId, $code)
{
    $attributeId = Mage::getResourceModel('eav/entity_attribute')->getIdByCode('catalog_category', $code);
    $entityType = Mage::getModel('eav/entity_type')->loadByCode('catalog_category');
    $attribute = Mage::getModel($entityType->getAttributeModel())->load($attributeId);
    $entityTable = $this->getTable($entityType->getEntityTable());
    $alias = 'table' . $code;
    $table = $entityTable . '_' . $attribute->getBackendType();
    $field = $alias . '.value';
    $this->getSelect()
        ->joinLeft(array($alias => $table),
                "{$joinOriginId} = {$alias}.entity_id AND {$alias}.attribute_id = " . $attribute->getAttributeId(),
                array($attribute->getAttributeCode() => $field)
        );
    return $this;
}
相关问题