2014-09-04 32 views
0

我的視圖讓用戶看到一個人的詳細信息,包括他們所在的家族。這是在DB中使用Person表,Family表和FamilyMembership鏈接表完成的。Yii將相關數據導入GridView

中的CActiveRecord模型人的關係是這樣的:

'families' => array(self::MANY_MANY, 'Family', 'familymembership(Person, Family)'), 

在我一個人控制,我想一個變量傳遞到具有在某種程度上的相關數據認爲TbGridView(CGridView但Bootstrap)會接受(一個數據提供者)。控制器調用模型人的getFamilies()函數:

public function getFamilies() { 
    // returns an array of Family objects related to this Person model 
    $familiesArray = $this->getRelated('families'); 
    // puts this array into a CArrayDataProvider 
    $families = new CArrayDataProvider($familiesArray); 
    return $families; 
} 

返回值可以追溯到控制器,然後穿過的RenderPartial()調用移交。視圖有一個TbGridView控件初始化是這樣的:

$this->widget('bootstrap.widgets.TbGridView', 
      array(
       //the CArrayDataProvider from the model function 
       'dataProvider' => $families, 
       'columns' => array(
        array(
         'name' => 'Family Name', 
         // Example field from Family model 
         'value' => '$data->familyName' 
        ) 
       ) 
     )); 

然而,在這樣做,我收到以下錯誤: 「屬性‘Family.id’沒有定義。 (D:\ wamp \ www \ yii \ framework \ base \ CComponent.php:130)'

家族模型沒有id屬性,我不明白爲什麼widget正在尋找這樣的東西。

這裏怎麼回事?

謝謝。

回答

1

Yii Class Reference引用的文檔,你必須提供一個keyField

Elements in the raw data array may be either objects (e.g. model objects) or associative arrays (e.g. query results of DAO). Make sure to set the keyField property to the name of the field that uniquely identifies a data record or false if you do not have such a field.

默認keyField將被設置爲「ID」,所以你需要與你的家庭模式的主鍵將其覆蓋:

<?php 
$familyDataProvider = new CArrayDataProvider($rawData, array(
    'keyField' => 'yourPkNameHere', 
)); 
+0

感謝您的幫助! – 2014-09-04 22:52:19