Joan Morillo
Joan Morillo

Reputation: 11

Yii2 Junction relation

I want to get all the groups that are not joint by an user throught another table. My tables are user, user_to_usergroup and usergroup.

Is there a way to get the opposite results from a query?

The code is as follows:

public function getGroupsNotJoint() {    
return $this- >hasMany(Usergroup::className(), 
['id' => 'group_id'])->viaTable('user_to_usergroup', ['user_id' => 'id']);
}

This code returns all the groups that a user belong, I just want the groups that the user doesn't belong.

Upvotes: 1

Views: 59

Answers (1)

arogachev
arogachev

Reputation: 33538

Name existing relation getGroups(), you can get the rest of the groups for current user by modifying this relation (applying additional condition):

public function getOtherGroups()
{
    return $this->getGroups()->andWhere(['!=', 'user_id', \Yii::$app->user->id]);
}

Upvotes: 1

Related Questions