Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FOS bundle - How to select users with a specific role?

Tags:

symfony

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?

like image 489
Visavì Avatar asked Jan 26 '12 10:01

Visavì


2 Answers

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(); } 
like image 120
Léo Benoist Avatar answered Nov 25 '22 16:11

Léo Benoist


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(); 
like image 34
Visavì Avatar answered Nov 25 '22 15:11

Visavì