mysql - Magento 为每个产品找到最深的类别

标签 mysql magento group-by

在我的产品网格页面上,我想为每个产品显示它所在的“最深”类别。

这是我到目前为止根据一些其他类似问题的主题得出的结论。

    $res = Mage::getSingleton('core/resource');
    $eav = Mage::getModel('eav/config');
    $nameattr = $eav->getAttribute('catalog_category', 'name');
    $nametable = $res->getTableName('catalog/category') . '_' . $nameattr->getBackendType();
    $nameattrid = $nameattr->getAttributeId();

    $collection
    ->joinTable('catalog/category_product',
    'product_id=entity_id', array('single_category_id' => 'category_id'),
    null,'left')

    ->joinTable('catalog_category_entity',
    "entity_id=single_category_id", array('cat_level' => 'level','cat_path' => 'path'),
    null,'left')

    //->addAttributeToSort('entity_id', 'ASC')
    //->addAttributeToSort('cat_level', 'ASC')
    //->groupByAttribute('entity_id')

    ->joinTable($nametable,
    "entity_id=single_category_id", array('single_category_name' => 'value'),
    "attribute_id=$nameattrid", 'left')
    ->printLogQuery(true);exit;

这给了我以下结果:

Screenshot MYSQL results

所以我得到了我的产品集合,并添加了三列。显然,对于 entity_id 310,“Fauteuils”是最深的类别。我现在唯一要做的就是根据最高 cat_level 按 entity_id 对结果进行“分组”。但是,“分组依据”并没有给我想要的结果。

谢谢

最佳答案

这是一个简单的解决方案,您可以从中汲取灵感:

$category  = $product->getCategory();
$path      = explode('/', $category->getPath());
$deepestId = $path[count($path) - 1];

$deepestCategory = Mage::getModel('catalog/category')->load($deepestId);

Zend_Debug::dump($deepestCategory->getData());exit;

您需要查看类别表中的 path 列,然后找到路径中的最后一个类别 ID。

关于mysql - Magento 为每个产品找到最深的类别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10007301/

相关文章:

mysql - 尝试上传图像时 Multer 出错

mysql - 选择与内连接条件不匹配的行

mysql - 如何获取列创建脚本工作台?

java - 转换错误

javascript - 向管理输入和文本区域添加字符数

python - Pandas - 使用 Groupby 列出新列中的数据列

group-by - mdx 按度量值范围分组

php - mysql_query 不返回任何内容,但可以手动使用 åæø

php - Magento:按产品 ID 获取分组产品的最低价格?

mysql - 如何在 MySQL 中获取每个玩家的半个世纪、世纪和双百的数量