Magento深入理解-Grid报错clause is ambiguous问题

piaoling  2011-07-26 16:01:09

我记得之前没少讲过Grid,今天在写Grid遇到这样一个错误,将解决办法分享下。

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

这个错误怎么来的呢,关键是clause is ambiguous。

使用Grid必须要设置一个Collection,往往这个Grid需要联表查询,就是写join语句。请看下面例子:

    protected function _getCollectionClass()
    {
        return 'sales/order_shipment_grid_collection';
    }
 
    protected function _prepareCollection()
    {
        $collection = G::getResourceModel($this->_getCollectionClass());
        $collection->getSelect()
        ->joinLeft(array('o'=>'sales_flat_order'),'main_table.order_id = o.entity_id','grand_total')
       ->joinLeft(array('st'=>'sales_flat_shipment_track'),'main_table.order_id = st.order_id',
                  array('carrier_code','number','shipped_time'));
 
        $this->setCollection($collection);
        return parent::_prepareCollection();
    }

这段例子是我改写后台配送模块时用到的。原来只是一个简单的表,因为需要跟COD结算、还要监督发货部门的效率。所以需要将订单金额、发货时间等等 联表查询出来,问题出在shipment表有个increment_id字段,而关联的order表同样也有这个increment_id字段。

按下面的这样来配置Grid:

        $this->addColumn('increment_id', array(
            'header'    => G::helper('sales')->__('Shipment #'),
            'index'     => 'increment_id',
            'type'      => 'text',
        ));

本来我们这里的increment id是物流号,而订单里的increment id是订单号,打开页面,Grid可以正常显示,但是当尝试搜索物流号的时候就会报错了,就是上面的错误。
于是开始找哇,几乎看遍了后台所有的grid,就不信找不到,终于出现了这样一段代码:

        $this->addColumn('created_at', array(
            'header'    =>G::helper('reports')->__('Created At'),
            'width'     =>'170px',
            'type'      =>'datetime',
            'index'     =>'created_at',
            'filter_index'=>'main_table.created_at',
            'sortable'  =>false
        ));
 
        $this->addColumn('updated_at', array(
            'header'    =>G::helper('reports')->__('Updated At'),
            'width'     =>'170px',
            'type'      =>'datetime',
            'index'     =>'updated_at',
            'filter_index'=>'main_table.updated_at',
            'sortable'  =>false
        ));

请看G_Adminhtml_Block_Report_Shopcart_Abandoned_Grid这个文件。
原来Column可以设置filter_index,之前自己还尝试’index’=>’main_table.increament_id’等等,原来这样就可了,于是上面我改的代码变成了这样:

        $this->addColumn('increment_id', array(
            'header'    => G::helper('sales')->__('Shipment #'),
            'index'     => 'increment_id',
            'filter_index' =>'main_table.increment_id',
            'type'      => 'text',
        ));

爽~~过滤正常了~~ :)

类别 :  magento(258)  |  浏览(3732)  |  评论(0)
发表评论(评论将通过邮件发给作者):

Email: