This article mainly introduces how Yii2hasOne () and hasone () implement three-table Association (two methods), which is very good and has reference value, for more information about how to use Yii2 hasOne () and hasOne () to implement three-table join, this article is of great reference value, for more information, see
Background:
There are two types of instances: group and user.
A group can have multiple users, and a user can also belong to multiple groups (many-to-many relationship)
The GroupUserRelation table is used to bind a group member relationship (id binding is used)
The fields include id, group_id, and user_id.
For an existing User table, you need to obtain information about all User groups to which the table belongs. you need to use hasMany () for multi-table Association.
User.id => GroupUserRelation.user_idGroupUserRelation.group_id => Group.id
Method 1
public function getGroup(){ return $this->hasMany(Group::className(), ['id' => 'group_id']) ->viaTable(GroupUserRelation::tableName(), ['user_id' => 'id']);}
Method 2
public function getGroup(){ return $this->hasMany(Group::className(), ['id' => 'group_id']) ->viaTable('groupUserRelation');}public function getGroupUserRelation(){ return $this->hasMany(GroupUserRelation::tableName(), ['user_id' => 'id']);}
The above is a detailed description of the two methods for implementing three-table Association in Yii2 hasOne () and hastwo (). For more information, see other related articles in the first PHP community!