symfony

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


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?


Solution

  • 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();
    }