簡體   English   中英

Yii CGridView,顯示來自相關模型的多個列,具有過濾功能

[英]Yii CGridView, displaying multiple columns from related model with filtering capability

我對yii很新,我碰到了以下問題。 我有2個相關的表, ClientTicketProduct具有以下結構:

ClientTicket

  • ID
  • ticket_name
  • CLIENT_ID
  • PRODUCT_ID

產品

  • ID
  • 類型
  • 模型

這兩個表通過將ClientTicket.product_id綁定到Product.id的外鍵相關聯。

問題

在ClientTicket的管理視圖中,我設法包含兩個產品列(品牌,型號),並為每個列顯示搜索框,但過濾未按預期工作。 例如:當我在兩個搜索框(品牌,型號)中的任何一個中搜索時,另一個搜索框自動填充我輸入的相同值(因此沒有搜索結果)。

ClientTicket模型:

    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),
    ));
}

ClientTicket Admin視圖文件:

<?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'
        ),

您的productbrand列具有相同的namevalues不同。 過濾器從name獲取字段名稱,除非您明確說明它,即創建自己的活動字段。 此外,您使用相同的屬性product_id來搜索search功能中的兩個字段。

Yii已經回答了如何使用相關模型進行過濾- 如何通過管理頁面上的外鍵/相關鍵列進行搜索?

對於其他用戶的參考,這是我如何讓它工作。 再次,謝謝topher的快速響應。 :)

內部ClientTicket模型:

  • 宣布一個名為$ brand的新公共變量
  • 在'=>'搜索'數組中,在rules()函數內添加'brand''safe' '
  • search()函數中添加了一個新標准,如下所示:
    $ criteria-> compare('product.brand',$ this-> brand,true);

在ClientTicket管理視圖文件中:

修改了產品品牌欄目:

array('name'=>'product_id',
    'header'=> 'Brand',
    'value'=>'$data->product->brand'
    ),

對此:

 array('name'=>'product.brand',
    'header'=> 'Brand',
    'filter'=>CHtml::activeTextField($model,'brand'),
    ),

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM