In order to implement some sort of ‘friendship’ relation between two users, I wanted to create a MANY_MANY relation from my user model to itself. Much to my surprise, the following actually works (well, kind of):
User.php
public function relations() {
return array(
'related' => array(
self::MANY_MANY, 'User', 'Relation(user1, user2)',
),
);
}
However, this property only returns the related users for which the current user is in the first column, and the related user is in the second column. I want this to be a symmetrical relationship, so that relations where the current user is in the second column are included as well. I can think of two ways to do this, but I don’t like either of them:
-
Inserting a relation twice into the relation table (user1, user2) and (user2, user1)
-
Creating another relation with swapped keys like so:
public function relations() {
return array(
'related' => array(
self::MANY_MANY, 'User', 'Relation(user1, user2)',
),
'related2' => array(
self::MANY_MANY, 'User', 'Relation(user2, user1)',
),
);
}
Is there a better way to make this relationship symmetrical without inserting duplicate data or having to access two separate model relations?