Using Relational AR to Get an OR Condition

I am using the Yii framework and ran into a problem creating a Friend / Connection style system. I have a standard user table and for storing friends I have a friends table with the following layout (corresponding FK, etc. Have been configured):

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

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

What I'm trying to do is use the Yii relational query to ultimately return the items that belong to friends. I currently have the following relation in the User model ...

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

However, this only returns β€œfriends” if the user ID is present in the userId field. If the user ID is in the friendId field, the friendship will not be recognized.

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

Also, is there a way to get Yii to return another identifier, so if user ID == userId it will return friendId, otherwise if user ID == friendId will return userId?

In the end, I'm trying to do something like:

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

Hope I have not embarrassed too much! Sorry for the poor explanation.

Thanks:)

+4
source share
2 answers

Follow the instructions here about creating the database command object, and then you can query the OR clause as follows:

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

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

 $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 about the structure of the models and the relationship between User and UserFriend . Do you have any relationship from UserFriend to User ? If so, you can use something like $userFriends->user0 after the code above.

CDbCriteria Details

find () method description

0
source

Source: https://habr.com/ru/post/1433059/


All Articles