A
A
Alexey2014-07-21 12:19:54
MySQL
Alexey, 2014-07-21 12:19:54

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]);
      }
    );

For example:
u_id1 = 1, u_id2 = 2, status = 0
The connection is found, but when another user (with u_id2) enters and starts searching for this request, he does not find anything because he is looking for his identifier in u_id1.
It is necessary that both u_id1 and u_id2 can find themselves in the record:
u_id1 = 1, u_id2 = 2, status = 0

Answer the question

In order to leave comments, you need to log in

2 answer(s)
F
Flaker, 2014-07-21
@azovl

This option:

// В модели User
public function getFriends()
    {
        return $this->hasMany(static::className(), ['id' => 'u_id1'])
            ->viaTable('{{%UserContact}}', ['u_id2' => 'id']);

    }

S
Sergey, 2014-07-21
@TsarS

Why not combine with a pivot table?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question