murinho
(Joamoll1)
1
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.
sidtj
(sdlins)
2
Please, look at this:
http://www.codeproject.com/Articles/33052/Visual-Representation-of-SQL-Joins
Specially at the [color=#111111]Left Excluding JOIN.[/color]
softark
(Softark)
3
@slinstj
Thank you for the link. It’s very instructive and I like it very much.
But, how do you implement this particular "relation"?
sidtj
(sdlins)
4
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.
softark
(Softark)
5
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.