I am trying to get only user with 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"
.
Your problem is that the User model in FOSUserBundle never actually has the ROLE_USER
.
FOS\\UserBundle\\Model\\UserInterface
const ROLE_DEFAULT = 'ROLE_USER';
FOS\\UserBundle\\Model\\User
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.
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
.
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
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.