2014-12-03 107 views
2

我正在使用sql server 2008和yii​​2。 爲了建立一個多對多的關係,我製作了一個交叉引用表,並加入了兩個查找表。 在生成CRUD之後,這是生成的模型關係。如何在yii2中使用多對多的關係以及如何將數據插入到橋表中

/** 
* @return \yii\db\ActiveQuery 
*/ 
public function getEmailPageLists() 
{ 
    return $this->hasMany(EmailPageList::className(), ['email_id' => 'id']); 
} 

/** 
* @return \yii\db\ActiveQuery 
*/ 
public function getPages() 
{ 
    return $this->hasMany(PageLists::className(), ['page_id' => 'page_id'])->viaTable('email_page_list', ['email_id' => 'id']); 
} 

現在我該如何鏈接這些表?我在哪裏可以使用link()函數? 我想在插入表格時插入橋表。

回答

1

這是一個多對多的關係的一個例子:

/** 
* @return \yii\db\ActiveQuery 
*/ 
public function getRecipes() 
{ 
    return $this->hasMany(Recipe::className(), ['id' => 'Recipe_id']) 
     ->viaTable('RecipeProduct', ['Product_id' => 'id'], function($query) { 
      return $query->where('RecipeProduct.status = "active"'); 
     }); 
} 

或者

/** 
* @return \yii\db\ActiveQuery 
*/ 
public function getProductProductCategories() 
{ 
    return $this->hasMany(ProductProductCategory::className(), ['Product_id' => 'id']); 
} 
/** 
* @return \yii\db\ActiveQuery 
*/ 
public function getCategories() 
{ 
    return $this->hasMany(ProductCategory::className(), ['id' => 'ProductCategory_id']) 
     ->via('productProductCategories'); 
} 

這是如何定義通過其他模型的關係的例子。在這種情況下,我通過上面定義的稱爲productProductCategories的關係將產品綁定到類別。

這是鏈接到活動記錄,滾動到機器人的鏈接部分http://www.yiiframework.com/doc-2.0/guide-db-active-record.html#working-with-relationships。我沒有嘗試通過多對多記錄進行鏈接。

+0

啊哈!我想我找到了我的解決方案。我面臨的主要問題是在橋表中插入數據,這是我爲多對多關係所做的。 我在控制器的create函數中創建了橋表模型類的對象,併爲它賦值.Voila !!!就是這樣!現在它會自動插入橋表中。 :) – Rabib 2014-12-08 05:33:53

+0

您是否嘗試過使用Link進行插入,而沒有將關係表作爲模型。我不相信,但我從來沒有嘗試過。 – 2014-12-08 07:11:17

+0

不,我沒有使用鏈接功能。只需從我的控制器功能插入數據。 – Rabib 2014-12-08 07:30:42

相關問題