I have added a few custom columns to the sales order grid.
SKU and product name were successfully added, appearing as expected in their respective rows.
Now when I add a product attribute that doesn't come from the sales_flat_order_item table, I get double entries populating for every row for these columns.
=> For example : I add custom_attr from the catalog_product_entity_varchar table. Now all three extra columns are doubled up:
SKU: 123,123
Name: example, example
custom_attr: blue,blue
I think the problem comes from the following code in my Observer, if anyone can spot it?
$collection = $observer->getOrderGridCollection();
$select = $collection->getSelect();
$select->joinLeft(array('payment' => $collection->getTable('sales/order_payment')), 'payment.parent_id=main_table.entity_id', array('payment_method' => 'method'));
$select->join('m_sales_flat_order_item', '`m_sales_flat_order_item`.order_id=`main_table`.entity_id', array('sku' => new Zend_Db_Expr('group_concat(`m_sales_flat_order_item`.sku SEPARATOR ", ")'),'name' => new Zend_Db_Expr('group_concat(`m_sales_flat_order_item`.name SEPARATOR ", ")') ));
$select->join('m_catalog_product_entity_varchar', '`m_catalog_product_entity_varchar`.attribute_id=163 AND `m_catalog_product_entity_varchar`.entity_id = `m_sales_flat_order_item`.`product_id`', array('custom_attr' => new Zend_Db_Expr('group_concat(`m_catalog_product_entity_varchar`.value SEPARATOR ",")')));
$select->group('main_table.entity_id');
Update
Thanks to the below responses I was able to reach a solution with a bit modification. The two joins worked as below.
$select->join('m_sales_flat_order_item','`m_sales_flat_order_item`.order_id=`main_table`.entity_id', array('sku' => new Zend_Db_Expr('`m_sales_flat_order_item`.sku'),'name' => new Zend_Db_Expr('`m_sales_flat_order_item`.name') ))->where('`m_sales_flat_order_item`.parent_item_id IS NULL');
$select->join(array('m_catalog_product_entity_varchar'),'(m_catalog_product_entity_varchar.entity_id = `m_sales_flat_order_item`.`product_id`) AND `m_catalog_product_entity_varchar`.attribute_id=163',
array('custom_attr' => 'm_catalog_product_entity_varchar.value'));