2011-12-16 37 views
1

如何在Yii框架中創建多模型CGridView。我搜查了Yii的文檔。如何創建多模型CGridView

下面是比如我需要的兩個表

表:user_master

+---------+----------+-------------+-------------+ 
| user_id | name  | email  | active  | 
| 1  | Darshit | [email protected] | true  | 
| 2  | Obed  | [email protected] | true  | 
| 3  | abmed | [email protected] | true  | 
| 4  | clutch | [email protected] | true  | 
| 5  | sirisb | [email protected] | true  | 
+---------+----------+-------------+-------------+ 

表:friend_master

+---------+-----------+--------------+-------------+ 
| user_id | friend_id | date_created | is_deleted | 
+---------+-----------+--------------+-------------+  
| 1  | 2  | 2011-12-14 | false  | 
| 1  | 5  | 2011-12-14 | false  | 
| 3  | 5  | 2011-12-14 | false  | 
| 2  | 4  | 2011-12-14 | false  | 
| 1  | 3  | 2011-12-14 | false  | 
| 5  | 2  | 2011-12-14 | false  | 
+---------+-----------+--------------+-------------+ 

我想網格是這樣的:

Desired Result

我創建了這兩個表的模型,但它們只顯示單個模型網格視圖。

所以,我沒有辦法做到這一點。任何幫助將是非常可觀的。

回答

4

它看起來像你不需要一個multimodel gridview。您根據需要給出的網格僅顯示一個模型的元素user_master。屬性「Friends」實際上屬於該模型,因爲它是與user_master表的每個特定實例相關的值。因此,您實際上可以將該屬性「Friends」想象爲user_master表中的額外列。您不需要將該行添加到表中,只需將其聲明爲模型中的屬性即可。以下行添加到由user_master模型的「關係」函數返回的數組:

'FriendsCount'=> array(self::STAT, 'friend_master', 'user_id'), 

你可以閱讀更多關於如何在這裏工作:http://www.yiiframework.com/doc/api/1.1/CActiveRecord/#relations-detail

簡而言之,關係的STAT類型只是檢索模型的統計值。在這種情況下,它只會計算與user_master模型的每個實例相關的好友數量。

現在,在您的CGridView定義中,您必須聲明要顯示的3列。這是在'columns'數組內完成的。當然,'user_id'和'name'將被識別爲正在顯示的模型的顯式聲明屬性,所以我們不需要關心它們。但對於「朋友」列,您可能需要明確指定要顯示的值。這樣做是簡單地使用數組:

<?php $this->widget('zii.widgets.grid.CGridView', array(
     ... 
    ... 
    'columns'=>array(
     'user_id', 
     'name', 
      array(
       'class'=>'CDataColumn', 
      'name'=>'Friends', 
      'value'=>'$data->FriendsCount', //The FriendsCount relation we declared        
      ), 
    ), 
)); 
?> 

您可能會注意到,使用這種基於陣列的語法,你可以聲明相當多才多藝列。

我希望你覺得這篇文章有用。

+0

真的很感謝您的回覆,我將使用您提供的解決方案。並會很快回復你..非常感謝@Alfredo – 2011-12-17 14:23:16