2012-08-23 24 views
1

我有幾個關係模型,我想要做的就是用我在DetailView中提供的別名搜索字段。它看起來像這樣Yii通過別名進行高級和內聯搜索

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

謝謝。

回答

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',例如:在columns

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

然後代替currency.short你可以把currencyshort,它將與過濾器,排序等工作

+0

Thx的答覆,我應該爲所有列我要搜索的虛擬領域?以及他們應該放在哪裏?在他們的模型中還是在將搜索它們的模型中? –

+0

是的,您可以爲與模型相關的所有排序/搜索列創建字段。你應該把它們放在搜索它們的模型中。 – Johnatan