doukao8851 2013-10-22 21:51
浏览 28
已采纳

Yii CGridView,显示来自相关模型的多个列,具有过滤功能

I'm pretty new to yii and I bumped into the following problem. I have 2 related tables, ClientTicket and Product with the following structure:

ClientTicket

  • id
  • ticket_name
  • client_id
  • product_id

Product

  • id
  • type
  • model
  • brand

The two tables are related through a foreign key which binds ClientTicket.product_id to Product.id.

The Problem

In the admin view of the ClientTicket I've managed to include two of the Product columns (brand, model) and have the search box display for each of them, but the filtering isn't working as expected. Ex: When I search in either of the two search boxes(brand, model), the other one populates automatically with the same value I typed (so no search results).

The ClientTicket model:

    public function relations()
{
    // NOTE: you may need to adjust the relation name and the related
    // class name for the relations automatically generated below.
    return array(
        'product' => array(self::BELONGS_TO, 'Product', 'product_id'),
        ........
    );
}

    public function search()
{
    // Warning: Please modify the following code to remove attributes that
    // should not be searched.

    $criteria=new CDbCriteria;

    ...
    $criteria->compare('product.model',$this->product_id, true);
    $criteria->compare('product.brand',$this->product_id, true);
    ...

    $criteria->with=array(..., 'product',);
    $criteria->together= true;

    return new CActiveDataProvider($this, array(
        'criteria'=>$criteria,
        'pagination' => array('pageSize' => 10),
    ));
}

The ClientTicket Admin view file:

<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'client-ticket-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
    'ticket_number',
    'ticket_date',
    array('name'=>'agent_id',
        'header'=> 'Agent',
        'value'=> '$data->ticket_agent->name',
        'filter'=>CHtml::listData(Agent::model()->findAll(), 'name', 'name'),
        ),
    ...
    array('name'=>'product_id',
        'header'=> 'Product',
        'value'=> '$data->product->model',
        ),
    array('name'=>'product_id',
        'header'=> 'Brand',
        'value'=>'$data->product->brand'
        ),

展开全部

  • 写回答

2条回答 默认 最新

  • doubi4617 2013-10-22 23:06
    关注

    Your productand brand columns both have the same name but different values. The filter obtains the field name from name unless you explicitly state it i.e create your own active field. In addition you are using the same attribute product_id to search both fields in your search function.

    How to filter using related models has been answered at Yii - how can I search by a column from foreign/related key on admin page?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?