How to specify model relations with conditions and more than one foreign key?

Case 1:

I have this entities:


  • idUser


  • idUserFrom

  • idUserTo

So, I want to declare a HAS_MANY relation in the User model, which has all the messages that the user received OR sent, but I don’t know how to specify two different foreign keys ( idUserFrom & idUserTo ) and a condition that states that the relation should join by idUserFrom, when idUserFrom its equal to isUser, and by idUserTo, when idUserTo is equal to idUser.

Case 2:

It’s a similar case, but with a MANY_MANY relation, with the following table:


  • idUser1

  • idUser2

The friendship relationship is bi-directional, meaning that (1,2) and (2,1) represent the same friendship relationship between users 1 and 2, and if one combination exists in the table, the other doesn’t, each friendship is represented by a single row in the friendship table.

To define a relation in the model, I would need to specify that the relation should join a User 1 with another User 2, where exists a Friendship that has ( user 1, user 2) OR ( user 2, user 1 )

The Yii documentation doesn’t explain this very well, and when it shows an example of using a ‘condition’ inside a relation, it uses a trivial example which doesn’t include foreign keys, such as ‘status=1’




public function relations()


	return array(

		'from' => array(self::BELONGS_TO, 'User', 'idUserFrom'),

		'to' => array(self::BELONGS_TO, 'User', 'idUserTo'),




public function relations()


	return array(

		'm_sent' => array(self::HAS_MANY, 'Message', 'idUserFrom'),

		'm_received' => array(self::HAS_MANY, 'Message', 'idUserTo'),



Ok great, but what I want is to have a single relation that brings all the messages sent OR recieved by a given user, not two separate relations.