Answer the question
In order to leave comments, you need to log in
How does HasMany work in Yii2?
The situation is as follows:
I implement the functionality of "friends" for users.
I have 2 tables User, UserContact.
User
`id` int(11) NOT NULL AUTO_INCREMENT,
`login` varchar(60) COLLATE utf8_unicode_ci NOT NULL,
`email` varchar(60) COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`id`),
UserContact
`u_id1` int( 11) NOT NULL,
`u_id2` int(11) NOT NULL,
PRIMARY KEY (`u_id1`,`u_id2`),
KEY `fk_user_contact_user_2` (`u_id2`) That is,
each user has many friends, just like other users have many friends, a many-to-many relationship.
How to describe this connection in Yii2?
At the moment I am using this code, but it is not correct, since the search is only for u_id2.
return $this->hasMany(User::className(), ['id' => 'u_id2'])->viaTable(
UserContact::tableName(),
['u_id1' => 'id'],
function ($query) use ($status) {
$query->where(['status' => $status]);
}
);
Answer the question
In order to leave comments, you need to log in
This option:
// В модели User
public function getFriends()
{
return $this->hasMany(static::className(), ['id' => 'u_id1'])
->viaTable('{{%UserContact}}', ['u_id2' => 'id']);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question