如何在Yii2中处理多对多关系 [英] How do I work with many-to-many relations in Yii2
问题描述
例如由于文档( http://www.yiiframework.com/doc-2.0/guide-db-active-record.html#relational-data ),您可以通过(one-many = company-zone)
这样的方式链接两个模型:>
For example in one-to-many due to documentation (http://www.yiiframework.com/doc-2.0/guide-db-active-record.html#relational-data) you can link two models in this way (one-many = company-zone)
:
$defaultZone = new Zone;
$defaultZone->name = Zone::DEFAULT_ZONE;
$company->link('zones', $defaultZone);
但是当您拥有像tbl_user_market(user_id, market_id)
这样的运输表时,它如何用于多对多关系?
But how it works for many-to-many relations when you have transit table like tbl_user_market(user_id, market_id)
?
推荐答案
在使用联结表进行多对多关系时,您必须
When using a junction table for many-to-many relations, you have to
- 定义关系
- 将两个模型链接在一起
在用户模型中定义以下关系函数:
In the User model define the following relation function:
public function getMarkets() {
return $this->hasMany(Market::className(), ['id' => 'market_id'])
->viaTable('tbl_user_market', ['user_id' => 'id']);
}
在市场"模型中定义以下关系函数:
In the Market model define the following relation function:
public function getUsers() {
return $this->hasMany(User::className(), ['id' => 'user_id'])
->viaTable('tbl_user_market', ['market_id' => 'id']);
}
最后,在保存两个模型之后,将它们链接在一起:
And finally, after saving both models, link them together:
$user = new User;
$user->name = 'Foo';
$user->save();
$market = new Market;
$market->name = 'Bar';
$market->save();
$user->link('markets', $market);
对link()
的调用将填充联结表.
The call to link()
will populate the junction table.
参考: http://www. yiiframework.com/doc-2.0/yii-db-baseactiverecord.html#link()-详细信息
这篇关于如何在Yii2中处理多对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!