按symfony2中的角色加载用户

时间:2014-07-18 17:57:01

标签: php symfony doctrine dql

如何编写按用户角色从DB加载所有用户的请求? 我使用三个表(users,role和user_role)与多对多关系。

如果您可以帮我在UserRepository中编写函数loadUsersByRole(),我将非常感激。

实体\用户

namespace Kombinator\UserBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;
use Doctrine\Common\Collections\ArrayCollection;

/**
 * Kombinator\UserBundle\Entity\User
 *
 * @ORM\Table(name="kombinator_users")
 * @ORM\Entity(repositoryClass="Kombinator\UserBundle\Entity\UserRepository")
 */
class User implements UserInterface, \Serializable
{
    /**
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=25, unique=true)
     */
    private $username;

   /**
    * @ORM\ManyToOne(targetEntity="Company")
    * @ORM\JoinColumn(name="company", referencedColumnName="id")
    */
    protected $company;

     /**
     * @ORM\ManyToMany(targetEntity="Role", inversedBy="users")
     *
     */
    private $roles;

    public function __construct()
    {
        $this->roles = new ArrayCollection();
    }

    public function getRoles()
    {
        return $this->roles->toArray();
    }

    public function getRole()
    {
        $roles=$this->roles->toArray();
        if(isset($roles[0])){return $roles[0];}
        else{return NULL;}
    }
...

UserRepository

    namespace Kombinator\UserBundle\Entity;

    use Symfony\Component\Security\Core\User\UserInterface;
    use Symfony\Component\Security\Core\User\UserProviderInterface;
    use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
    use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
    use Doctrine\ORM\EntityRepository;
    use Doctrine\ORM\NoResultException;
    use Doctrine\ORM\Query\ResultSetMappingBuilder;
    use Kombinator\UserBundle\Controller\Paginator;
    use Kombinator\UserBundle\Entity\Filter;
    use Kombinator\UserBundle\Entity\Role;


    /**
     * UserRepository
     */
    class UserRepository extends EntityRepository implements UserProviderInterface
    {

        public function loadUserByUsername($username)
        {
            $q = $this
                ->createQueryBuilder('u')
                ->select('u, r')
                ->leftJoin('u.roles', 'r')
                ->where('u.email = :email AND u.status = 1')
                ->setParameter('email', $username)
                ->getQuery();

            try {
                $user = $q->getSingleResult();
            } catch (NoResultException $e) {
                $message = sprintf('Unable to find an active ... by "%s".',$username);
                throw new UsernameNotFoundException($message, 0, $e);
            }

            return $user;
        }


        public function findAllActiveJoinedToCompany($company)
        {
            $query = $this->getEntityManager()
                ->createQuery('
                    SELECT p, c FROM KombinatorUserBundle:User p
                    JOIN p.company c WHERE p.company='.$company);

            try {
                return $query;
            } catch (\Doctrine\ORM\NoResultException $e) {
                return null;
            }
        }

实体\作用

namespace Kombinator\UserBundle\Entity;

use Symfony\Component\Security\Core\Role\RoleInterface;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Table(name="kombinator_role")
 * @ORM\Entity()
 */
class Role implements RoleInterface
{
    /**
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id()
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @ORM\Column(name="name", type="string", length=30)
     */
    private $name;

    /**
     * @ORM\Column(name="role", type="string", length=20, unique=true)
     */
    private $role;

    /**
     * @ORM\ManyToMany(targetEntity="User", mappedBy="roles")
     */
    private $users;

    public function __construct()
    {
        $this->users = new ArrayCollection();
    }

    /**
     * @see RoleInterface
     */
    public function getRole()
    {
        return $this->role;
    }


    /**
     * Get id
     *
     * @return integer 
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set name
     *
     * @param string $name
     * @return Role
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get name
     *
     * @return string 
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Set role
     *
     * @param string $role
     * @return Role
     */
    public function setRole($role)
    {
        $this->role = $role;

        return $this;
    }

    /**
     * Add users
     *
     * @param \Kombinator\UserBundle\Entity\User $users
     * @return Role
     */
    public function addUser(\Kombinator\UserBundle\Entity\User $users)
    {
        $this->users[] = $users;

        return $this;
    }

    /**
     * Remove users
     *
     * @param \Kombinator\UserBundle\Entity\User $users
     */
    public function removeUser(\Kombinator\UserBundle\Entity\User $users)
    {
        $this->users->removeElement($users);
    }

    /**
     * Get users
     *
     * @return \Doctrine\Common\Collections\Collection 
     */
    public function getUsers()
    {
        return $this->users;
    }
}

RoleRepository

namespace Kombinator\UserBundle\Entity;

use Doctrine\ORM\EntityRepository;

/**
 * RoleRepository
 */
class RoleRepository extends EntityRepository
{
    public function findAll()
    {
        $query = $this->getEntityManager()
            ->createQuery('
                SELECT p FROM KombinatorUserBundle:Role p
                ORDER BY p.id'
            );

        try {
            return $query->getResult();
        } catch (\Doctrine\ORM\NoResultException $e) {
            return null;
        }
    }
}

1 个答案:

答案 0 :(得分:0)

当涉及多对多关系时,您应该在查询中使用MEMBER OF子句:

    public function loadUsersByRole($roleId)
    {
        $q = $this
            ->createQueryBuilder('u')
            ->select('u, r')
            ->leftJoin('u.roles', 'r')
            ->where(':roleId MEMBER OF u.roles AND u.status = 1')
            ->setParameter('roleId', $roleId)
            ->getQuery();

        return $q->getResult();
    }