Yii高级和通过别名的内联搜索

时间:2012-08-23 10:21:44

标签: yii

我有几个关系模型,我想要做的是使用我在DetailView中提供的别名搜索字段。看起来像这样

<?php $this->widget('bootstrap.widgets.BootGridView',array(
    'id'=>'operations-grid',
    'dataProvider'=>$model->search(),
    'filter'=>$model,
    'columns'=>array(
        'operationType.name:raw:Operation',
        'creation_date:datetime',
        'modification_date:datetime',
        'ammount_usd:raw:Ammount',
        'currency.short',
        /*

        'client_id',
        'organization_id',
        */
        array(
            'class'=>'bootstrap.widgets.BootButtonColumn',
        ),
    ),
)); ?>

我想要的是能够使用currency.short等列的别名搜索行。这样做的正确方法是什么?试图像这样修改search()方法..但我想我错过了什么。

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

    $criteria=new CDbCriteria;

    $criteria->compare('creation_date',$this->creation_date,true);
    $criteria->compare('modification_date',$this->modification_date,true);
    $criteria->compare('ammount',$this->ammount,true);
    $criteria->compare('ammount_usd',$this->ammount_usd,true);
    $criteria->compare('currency_id',$this->currency_id);
    $criteria->compare('operation_type',operationType::model()->name);
    $criteria->compare('client_id',$this->client_id);
    $criteria->compare('organization_id',$this->organization_id);
$criteria->compare('comment',$this->comment);
    return new CActiveDataProvider($this, array(
        'criteria'=>$criteria,
    ));
}

感谢。

1 个答案:

答案 0 :(得分:3)

您必须为该属性创建一个虚拟字段。例如,在您的主模型中:

private _currencyshort = null;
public function setCurrencyshort($value) {
    $this->_currencyshort = $value;
}
public function getCurrencyshort() {
    if ($this->_currencyshort === null && $this->currency != null)
    {
        $this->_currencyshort = $this->currency->short
    }
    return $this->_currencyshort;
}
public function search() {
    $criteria=new CDbCriteria;
    $criteria->with = array('currency'); // add more elements to array if you want to search by more relations
    $criteria->compare('currency.short',$this->currencyshort);
    // You can also add this field to your sorting criteria
    // ... etc
}

此外,您必须将currencyshort添加到主模型的rules()方法中,并指向'on'=>'search'所指的行,例如:

array('currencyshort', 'safe', 'on'=>'search'),

然后在columns而不是currency.short,您可以放置​​currencyshort,它可以使用过滤器,排序等。