Two methods for implementing three-table Association are described in detail in Yii2hasOne () and hastwo ().

Source: Internet
Author: User
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!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.