Many-to-many relationships from an entity to itself

s22.postimg.org/xb03rcg9t/diagram.png

I have a table called User and a junction table called Friend uniting User to itself.

I have these two classes User and Friend and I put this code inside of User:


public function getFriends()

{

    return $this->hasMany(Friend::className(), ['userId' => 'id'])->viaTable('friend', ['friendId' => 'id']);

}



I have nothing in the model Friend, because Friend is a junction table. Would this work? There are no pointers in the documentation for particular cases like this one.

A ‘User’ may have many friends, but they are instances of ‘User’.




    return $this->hasMany(User::className(), ...



Thank you. I only need to change the class name and that’s it? I can delete my Friend model and it will still work?

Yes, but you’d better not to delete Friend model, since you may want to use it when you manage (add and remove) friends.