4
votes

I'm using the Yii framework and have come across an issue whilst building a Friend/Connection style system. I have a standard users table and to store friends I have a friends table with the following layout (the appropriate FKs etc have been set up):

id | userId | friendId | and some other fields...

As the "friend" is mutual - so, if user A is a friend with user B, then user B is a friend with user A - therefore there is only ever one entry per "friendship".

What I'm trying to do is use Yii's relational query to eventually return items which belong to friends. Currently I have the following relation in the User model...

'friends' => array(self::HAS_MANY, 'UserFriend', 'userId'),

However that only returns 'friends' if the user's ID is present in the userId field. If the user's ID is in the friendId field then the "friendship" won't be recognised.

Is there a way to query using "OR" - for example: if user's ID == userId OR user's ID == friendId then return that entry?

In addition, is there a way to get Yii to return the other ID, so if user's ID == userId it will return friendId, else if user's ID == friendId it will return userId?

I'm eventually trying to do something like:

$userModel = User::model()->findByPk(Yii::app()->user->id); // user's model
$userFriends = $userModel->with(items)->friends; // return friends with their items

Hopefully I haven't confused too many! Sorry for the poor explanation

Thanks :)

2

2 Answers

0
votes

Follow the instructions here on creating a database command object, and then you can query with an OR condition as follows:

$command->where(array('OR', 'userID = :userID', 'userID = :friendID'), array(':userID' => $userID, ':friendID' => $friendID));
0
votes

Do you want get all friends of current user of your app? You can use CDbCriteria and method find(). Something like this:

$criteria = new CDbCriteria;
$criteria->addCondition('id = :userid');
$criteria->addCondition('friendid = :userid', 'OR'); // OR - the operator to join different conditions. Defaults to 'AND'.
$criteria->params = array(':userid' => Yii::app()->user->id);
$userFriends = UserFriend::model()->find($criteria);

But I'm not sure in your User and UserFriend models structure and mutual relations. Have you some relation from UserFriend to User? If so, than you can use something like $userFriends->user0 after code above.

CDbCriteria details

find() method details