Rabib
Rabib

Reputation: 430

How to work with many to many relationship in yii2 and how to insert data into bridge tables

I am working with sql server 2008 and yii2. To make a many-to-many relationship I have made a cross-reference table to join with two look up tables. And after CRUD generation this is model relation generated.

/**
 * @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']);
}

Now how can I link those tables? And where can I use the link() function? I want to insert to the bridge tables when I insert into table.

Upvotes: 2

Views: 4717

Answers (1)

Mihai P.
Mihai P.

Reputation: 9357

This is an example of a many to many relation:

/**
 * @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"');
        });
}

Or

/**
 * @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');
}

This is an example of how to define a relation through another model. In this case I have tied the product to categories through the relation called productProductCategories that is defined above.

This is the link to the Active record, scroll to the bot to the link part http://www.yiiframework.com/doc-2.0/guide-db-active-record.html#working-with-relationships. I have not tried to link through a many to many record.

Upvotes: 1

Related Questions