Junction relation

Hi all,

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.

Please, look at this:

http://www.codeproject.com/Articles/33052/Visual-Representation-of-SQL-Joins

Specially at the [color=#111111]Left Excluding JOIN.[/color]

@slinstj

Thank you for the link. It’s very instructive and I like it very much.

But, how do you implement this particular "relation"?

I have not done this using relations, but I use to do queries like this:




$r = User::find()

            ->leftJoin('user_to_usergroup uug', 'user.id = uug.user_id') // LEFT JOIN user_to_usergroup AS uug ON user.id = uug.user_id

            ->onCondition('uug.id IS NULL') // WHERE clause

            ->asArray() //optional

            ->all();

Now you should be able to achieve your target. It is up to you.

Thank you. I got it.

It’s probably impossible to implement it as a relation. But, once agin, I really like the idea of “exclusive joins” stated in the article.

@murinho sorry for hijacking the topic.