我正在尝试将一些 catalog/category
属性左连接到 sales/order_item
集合。
例如:满意的结果会让我将类别名称添加到订单项目数据中。
- 我知道我可以使用类别平面表,但我需要知道是否可以加入 EAV 集合以及如何加入。
- 它必须通过一个 mysql 查询来完成(不是通过遍历订单项或类似的东西...)
- 我知道如果产品有多个类别,可能会导致行重复,这正是我需要的。
提前致谢!
最佳答案
这就是您在 Magento 世界中的做法。注意集合中的“分组依据”。这是因为在左连接中,当同一个主键有多个结果时,Varien_Data_Collection 会抛出一个错误,指出具有该 ID 的项目已经存在。无论如何,我已经为您编写并测试了它。
我的答案还获取类别名称的存储值,如果存储值不存在,则回退到默认值。
<?php
include 'app/Mage.php';
Mage::app();
$itemModel = Mage::getModel('sales/order_item');
$itemResource = $itemModel->getResource();
$categoryProductTable = $itemResource->getTable('catalog/category_product');
$categoryModel = Mage::getModel('catalog/category');
$categoryResource = $categoryModel->getResource();
$name = $categoryResource->getAttribute('name');
$nameTable = $name->getBackendTable();
$defaultStoreId = Mage_Core_Model_App::ADMIN_STORE_ID;
$collection = $itemModel->getCollection();
$collection->getSelect()->joinLeft(array('category_product_table' => $categoryProductTable), 'main_table.product_id = category_product_table.product_id', array());
$collection->getSelect()->joinLeft(array('store_category_name_table' => $nameTable),
"store_category_name_table.entity_id = category_product_table.category_id AND
store_category_name_table.attribute_id = {$name->getAttributeId()} AND
store_category_name_table.entity_type_id = {$name->getEntityTypeId()} AND
store_category_name_table.store_id = main_table.store_id",
array()
);
$collection->getSelect()->joinLeft(array('default_category_name_table' => $nameTable),
"default_category_name_table.entity_id = category_product_table.category_id AND
default_category_name_table.attribute_id = {$name->getAttributeId()} AND
default_category_name_table.entity_type_id = {$name->getEntityTypeId()} AND
default_category_name_table.store_id = {$defaultStoreId}",
array()
);
$collection->getSelect()->columns(array('category_name' => new Zend_Db_Expr('COALESCE(store_category_name_table.value,default_category_name_table.value)')));
$collection->getSelect()->group('main_table.item_id');
echo $collection->getFirstItem()->getCategoryName();
关于php - Magento:如何将 'catalog/category' 字段左连接到 'sales/order_item' 集合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37238512/