mysql - 获取产品级别最低的子类别

标签 mysql magento

我正在尝试加载与产品关联的所有类别,但只应选择最深的子类别。例如,产品与类别 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/

相关文章:

java - JPA 不返回 MySQL varbinary 字段的 UUID "Text"值

php - 使用 mysql 连接查询努力获取月份名称

php - 找不到类 'Zend_Measure_Weight' - Magento

php - Magento 客户网格 - 掩码电子邮件地址

Magento 订单导入/导出

Magento 2 在 Nginx 子文件夹中

php - 更新多个用户的表

mysql - 导入带有重复键的 MySQL 记录

MySQL从另一个表中获取最近的列

css - magento - 布局更新 xml 以添加删除或修改元素类名称