Get product's category ids and names
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.
Here is the basic query:
$select = $this->_getReadAdapter()->select()
->from($this->_productCategoryTable, 'category_id')
->where('product_id=?', $product->getId());
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_categ开发者_如何学JAVAory_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');
Then you can simply traverse the collection:
foreach($categories as $category) {
var_dump($category->getName());
}
I found this post: Joining an EAV table and made the function, which will add the category join query, use it from the collection.
Just call this function from the code this way:
// To join the name of category
$this->joinCategoryAttribute('<your table alias>.category_id', 'name');
And this is the function:
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;
}
精彩评论