當你想用CGridView控件來生成一個Grid表格的時候,是很是方便的,你只須要簡單的指定幾個屬性就能夠了,好比:
html
$this->widget('zii.widgets.CGridView', array(
'id'=>'order-grid-view',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
'id',
'customer_cd'
),
)ide
問題是,當你須要多多表進行查詢的時候,filter就須要多做一點工做了,很遺憾,我沒有找到Yii官方對此問題的簡易方法,因此,只能靠迂迴的方式了。
首先,讓關聯表字段顯示在Grid表格裏面很容易,你能夠在dataProvider屬性加上關聯表,而後columns屬性裏直接加上要顯示的關聯表屬性就能夠,好比,修改後的dataProvider爲
'dataProvider'=>$model->with('relationNameToOtherTable')->search(),
修改後的columns屬性爲:
'columns'=>array(
'id',
'customer_cd',
'customer_nm'=>array(
'name'=>'relationNameToOtherTable.customer_nm',
),
),
但這時的customer_nm是不具有filter域的this
解決方法以下:(修改主表對應的Model類)
1)手動爲主表增長關聯表屬性,public $this->customer_nm;
2) 修改search()方法,增長以下兩行:$criteria->with = 'relationNameToOtherTable';//relationNameToOtherTable是你在relations裏面定義的鍵值
$criteria->compare('customer_nm', $this->customer_nm);
3)增長afterFind()方法到主表的model類,方法內容以下:$this->customer_nm = $this->relationNameToOtherTable->customer_nm;
這時,你就能夠不像前面寫的那樣修改dataProvider和columns了,由於你手動增長的那個屬性已經把關聯表的字段屬性加進來了,直接用就能夠了,最終view代碼以下:
'dataProvider'=>$model->search();
'columns'=>array(
'id',
'customer_cd',
'customer_nm'=>array(
'name'=>'relationNameToOtherTable.customer_nm',
),
),
ok, that's all, not the best solution, but it works any way, well if you have some good ideas for this kind of problem feel free to tell me, thanks a lot!!url