我正在尝试加载与产品关联的所有类别,但只应选择最深的子类别。例如,产品与类别 women > trousers > jeans
相关联,并且只有 jeans
应该可见。
到目前为止,我想出的代码返回了正确的查询,但是在访问集合时,抛出了 sql 错误: SQLSTATE[42S22]: 未找到列:1054 Unknown column 'cat_path' in 'on Clause'
/* @var $_categoryNames Mage_Catalog_Model_Resource_Category_Collection */
$_categoryNames = $_product->getCategoryCollection();
$_categoryNames
->joinTable(
'catalog/category',
"entity_id = entity_id",
array('cat_path' => 'path')
)
->getSelect()
->where(
"cat_path not like( CONCAT( path, '/%' ) )"
);
die($_categoryNames->getSelect());
更新: 感谢 blmage,我至少能够找到一条 sql 语句来获取正确的类别:
SELECT *
FROM `catalog_category_entity`e
WHERE (SELECT COUNT(`entity_id`)
FROM `catalog_category_entity`c
WHERE c.path LIKE (CONCAT(e.path,'%'))
)=1
最佳答案
我的解决方案现在使用子选择而不是联接。可能还有一些地方需要改进,但它对我有用。
$_categoryIds = $_product->getCategoryIds();
/** @var $read Varien_Db_Adapter_Interface */
$read = Mage::getSingleton('core/resource')
->getConnection('core_read');
$_categoryIdSelect=$read->select()
->from(
array(
'c' => $_categories->getTable('catalog/category')
),
'COUNT(e.entity_id)'
)
->where('entity_id IN (?)', $_categoryIds)
->where(
"c.path LIKE (CONCAT(e.path,'%'))"
);
/* @var $_categoryNames Mage_Catalog_Model_Resource_Category_Collection */
$_categoryNames = $_product->getCategoryCollection();
$_categoryNames->getSelect()
->where(
'2 > (?)',
new Zend_Db_Expr($_categoryIdSelect)
);
关于mysql - 获取产品级别最低的子类别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17367487/