获得产品最低级别的子类别

时间:2013-06-28 14:46:40

标签: mysql magento

我正在尝试加载与产品相关联的所有类别,但只应选择最深的子类别。例如,产品与类别women > trousers > jeans相关联,只有jeans应该可见。

到目前为止,我提出的代码返回正确的查询,但在访问集合时会抛出sql错误:SQLSTATE[42S22]: Column not found: 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

2 个答案:

答案 0 :(得分: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)
            );

答案 1 :(得分:0)

试试这个

$path = "/abc/example";

$_categoryNames->addFieldToFilter('cat_path', array('nlike' => $path));