2014-02-06 119 views
0

我一直在關注this教程,以建立業務模型和類別模型之間的多種關係。Yii many_many關係不能始終工作

我的表是:

business[id (PK),name,date,...] 
business_category[businessID (FK to business.id), categoryID (FK to category.ID)] 
category[id (PK), name, date,...] 

在我的商業模式我有

public function relations() 
{ 
    return array(
     'categories'=>array(self::MANY_MANY, 'Category', 
          'business_category(categoryID,businessID)'), 
    ); 
} 

,在我的分類模型我有

public function relations() 
{ 
    return array(
     'businesses'=>array(self::MANY_MANY, 'Business', 
          'business_category(categoryID,businessID)'), 
    ); 
} 

當我傳給CListView部件

'dataProvider'=>new CActiveDataProvider('Business', array(
           'data'=>$model->businesses)), 

其中$model是一個分類模型,然後我就可以遍歷每個企業正常的類別:foreach($data->categories as $category)

當我有$model = $this->loadModel($id)不過,$model->categories沒有任何結果。

什麼可能是錯的?

+0

是否嘗試過跳過loadModel()並執行$ model = new YOURMODELNAME :: model() - > findByPk($ pk)而不是? –

回答

0

假設你已經完成了var_dump $模型並確保它不是NULL,並且實際上有一個從loadModel()返回的模型,我懷疑這可能是由於業務關係中的列的順序。嘗試:

分類型號:

public function relations() 
{ 
    return array(
     'businesses'=>array(self::MANY_MANY, 'Business', 
          'business_category(businessID,categoryID)'), // Swapped order of columns 
    ); 
} 
0

我不好......我是從一個查詢和多數民衆返回多條記錄,爲什麼$model->categories不工作。