Magento – Column ‘store_id’ in where clause is ambiguous when adding custom order attribute to grid and changing store

order-collectionorder-gridsales-order

I have created a custom order attribute and I am now able to show it in the sales order grid; my previous question: Adding custom sales order attribute to order grid

If I were to change the drop down of Purchased From (Store) and try to filter the grid by a specific store, I get redirect back to the dashboard view in backend and when I revisit the sales order grid, I start getting this error:

SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'store_id' in where clause is ambiguous

I believe the issue is with the way I join onto the sales_flat_order table:

protected function _prepareCollection()
{
    $collection = Mage::getResourceModel($this->_getCollectionClass());
    $select = $collection->getSelect();
    $select->joinLeft(array
    (
        'order' => Mage::getModel('core/resource')->getTableName('sales/order')),
        'order.entity_id=main_table.entity_id',
        array('sales_rep' => 'sales_rep')
    );
    $this->setCollection($collection);
    return parent::_prepareCollection();
}

But I am not sure how to solve this. Any ideas?

Best Answer

use below code just before the $this->setCollection($collection);

$collection->addFilterToMap('store_id', 'main_table.store_id');

Second Solution edit your column code:

if (!Mage::app()->isSingleStoreMode()) {
            $this->addColumn('store_id', array(
                'header'    => Mage::helper('sales')->__('Purchased From (Store)'),
                'index'     => 'store_id',
                'type'      => 'store',
                'store_view'=> true,
                'display_deleted' => true,
                'filter_index' => 'main_table.store_id',
            ));
        }

hope this helps you