我正在尝试将一些catalog/category
属性左联接到sales/order_item
集合。
例如:令人满意的结果将让我将category-name添加到订单商品数据中。
提前致谢!
答案 0 :(得分:2)
这就是你在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();
答案 1 :(得分:1)
$resource = Mage::getSingleton('core/resource');
$readConnection = $resource->getConnection('core_read');
$sql = 'SELECT `main_table`.*, `products`.*, `cname`.* FROM `sales_flat_order_item` AS `main_table`
LEFT JOIN `catalog_category_product` AS `products` ON main_table.product_id=products.product_id
LEFT JOIN `catalog_category_entity_varchar` AS `cname` ON `products`.`category_id`=`cname`.`entity_id`
';
$result = $readConnection->fetchAll($sql);