[英]Symfony FosUserBundle show only user with role == ROLE_USER
I am trying to get only user with ROLE_USER
. 我试图只让用户使用ROLE_USER
。
I have this in my controller: 我在我的控制器中有这个:
$query = $this->getDoctrine()->getEntityManager()
->createQuery(
'SELECT u FROM StageUserBundle:User u WHERE u.roles LIKE :role'
)->setParameter('role', '%"ROLE_USER"%'
);
$users = $query->getResult();
It worked with ROLE_ADMIN
instead of ROLE_USER
but I need to show only User.getRoles()== "ROLE_USER"
. 它使用ROLE_ADMIN
而不是ROLE_USER
但我只需要显示User.getRoles()== "ROLE_USER"
。
Your problem is that the User model in FOSUserBundle never actually has the ROLE_USER
. 您的问题是FOSUserBundle中的用户模型实际上从未实际拥有ROLE_USER
。
FOS\\UserBundle\\Model\\UserInterface FOS \\ UserBundle \\型号\\的UserInterface
const ROLE_DEFAULT = 'ROLE_USER';
FOS\\UserBundle\\Model\\User FOS \\ UserBundle \\型号\\用户
public function addRole($role)
{
$role = strtoupper($role);
if ($role === static::ROLE_DEFAULT) {
return $this;
}
if (!in_array($role, $this->roles, true)) {
$this->roles[] = $role;
}
return $this;
}
....
public function getRoles()
{
$roles = $this->roles;
foreach ($this->getGroups() as $group) {
$roles = array_merge($roles, $group->getRoles());
}
// we need to make sure to have at least one role
$roles[] = static::ROLE_DEFAULT;
return array_unique($roles);
}
When you getRoles
it add the ROLE_USER
as a default and when you addRole
it check to see if the role is ROLE_USER
and then skips if it does. 当你getRoles
它添加ROLE_USER
作为默认值,当你addRole
它检查角色是否是ROLE_USER
,然后跳过,如果它。
In reality every user on your system will have the ROLE_USER
so to find all users with the role you can just do a SELECT u FROM StageUserBundle:User u
. 实际上,系统中的每个用户都将拥有ROLE_USER
以便找到具有该角色的所有用户,您只需执行SELECT u FROM StageUserBundle:User u
。
I Found the solution to my problem . 我找到了解决问题的方法。 i changed this in my controller : 我在我的控制器中改变了这个:
$query = $this->getDoctrine()->getEntityManager()
->createQuery('SELECT u FROM StageUserBundle:User u WHERE NOT u.roles LIKE :role'
)->setParameter('role', '%"ROLE_ADMIN"%' );
$users = $query->getResult();
Hope this will help. 希望这会有所帮助。
I'm not a SQL guru, but I think this case it's hard because the roles
field is a json
type 我不是SQL大师,但我认为这种情况很难,因为roles
字段是json
类型
You can try this 你可以试试这个
$query = $this->getDoctrine()->getEntityManager()
->createQuery(
'SELECT u FROM StageUserBundle:User u
WHERE u.roles LIKE :role
AND NOT u.roles LIKE :role2'
)->setParameter('role', '%"ROLE_USER"%'
)->setParameter('role2', '%ADMIN%'
);
$users = $query->getResult();
It will look for roles
that contains "ROLE_USER"
and not ADMIN
它将查找包含"ROLE_USER"
而不是ADMIN
roles
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.