I am using the FOS bundle and I want to retrieve all users with a given ROLE from the database.
What is the best way to do this?
Just add this in your UserRepository or replace $this->_entityName
by YourUserBundle:User
:
/** * @param string $role * * @return array */ public function findByRole($role) { $qb = $this->_em->createQueryBuilder(); $qb->select('u') ->from($this->_entityName, 'u') ->where('u.roles LIKE :roles') ->setParameter('roles', '%"'.$role.'"%'); return $qb->getQuery()->getResult(); }
If you are using FOSUser Groups you should use:
/** * @param string $role * * @return array */ public function findByRole($role) { $qb = $this->_em->createQueryBuilder(); $qb->select('u') ->from($this->_entityName, 'u') ->leftJoin('u.groups', 'g') ->where($qb->expr()->orX( $qb->expr()->like('u.roles', ':roles'), $qb->expr()->like('g.roles', ':roles') )) ->setParameter('roles', '%"'.$role.'"%'); return $qb->getQuery()->getResult(); }
Well, if there is no better solution, I think I will go to a DQL query:
$query = $this->getDoctrine()->getEntityManager() ->createQuery( 'SELECT u FROM MyBundle:User u WHERE u.roles LIKE :role' )->setParameter('role', '%"ROLE_MY_ADMIN"%'); $users = $query->getResult();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With