[英]Query in ManyToMany Relation Doctrine2
This is driving me crazy. 这真让我抓狂。
I have a normal Symfony2 Security System, with User and Role entities with a ManyToMany relation between them. 我有一个普通的Symfony2安全系统,其中的用户和角色实体之间具有ManyToMany关系。
Lets suppose that i have 3 roles in the database, ROLE_1
, ROLE_2
and ROLE_3
. 假设我在数据库中有3个角色, ROLE_1
, ROLE_2
和ROLE_3
。
How can i retrieve all Users that dont have ROLE_3
for example ? 例如,如何检索没有ROLE_3
所有用户?
I already tried something like: 我已经尝试过类似的东西:
$qb->innerJoin('u.roles', 'r , 'WITH', $qb->expr()->notIn('r.id', ':roles')))
->setParameter('roles', array(3));
My Question is, how can i Query in the JoinTable ? 我的问题是,如何在JoinTable中查询?
This is more of a SQL question than it is a Symfony or Doctrine question. 这比Symfony或教义问题更像是一个SQL问题。 The first solution that comes to mind is a subquery, although that may or may not be the most efficient way to handle this problem. 我想到的第一个解决方案是子查询,尽管这可能是也可能不是处理此问题的最有效方法。 Something like this: 像这样:
SELECT username
FROM users
WHERE users.id NOT IN (
SELECT users.id
FROM users
INNER JOIN user_roles
ON users.id = user_roles.user_id
INNER JOIN roles
ON user_roles.role_id = roles.id
WHERE roles.id NOT IN (1,2)
);
Where 1 and 2 are the IDs of the role you want to include in your results, and user_roles
is the bridge table between users and roles. 其中1和2是要包含在结果中的角色的ID, user_roles
是用户和角色之间的桥梁表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.