使用Doctrine 2,我有以下查询:
/**
* @param Organization $organization
* @param User $user
* @return \Doctrine\ORM\QueryBuilder
*/
public function getFindByOrganizationQueryBuilder(Organization $organization, User $user)
{
$builder = $this
->createQueryBuilder('u')
->leftJoin('u.roles', 'r')
->where($this->createQueryBuilder('u')->expr()->orX(
$this->createQueryBuilder('u')->expr()->notIn('r.role', array('ROLE_SUPER_ADMIN', 'ROLE_ADMIN')),
$this->createQueryBuilder('u')->expr()->isNull('r')
))
;
return $builder;
}
这不能按预期工作,并返回至少有一个角色与ROLE_ADMIN或ROLE_SUPER_ADMIN不同的用户
或者,我试图用
替换where子句->where('r.role <> 'ROLE_ADMIN')
->andWhere('r.role <> 'ROLE_SUPER_ADMIN')
然后它不会返回没有角色的用户。
如何更改查询,以便返回任何没有ROLE_ADMIN或ROLE_SUPER_ADMIN的用户?
非常感谢!
答案 0 :(得分:2)
您需要合并OR
和AND
声明:
/**
* @param Organization $organization
* @param User $user
* @return \Doctrine\ORM\QueryBuilder
*/
public function getFindByOrganizationQueryBuilder(Organization $organization, User $user)
{
$builder = $this->createQueryBuilder('u');
$builder
->leftJoin('u.roles', 'r')
->where($builder->expr()->orX(
$builder->expr()->andX(
$builder->expr()->neq('r.role', 'ROLE_SUPER_ADMIN'),
$builder->expr()->neq('r.role', 'ROLE_ADMIN')
),
$builder->expr()->isNull('r')
))
;
return $builder;
}
答案 1 :(得分:-1)
找到方法:
/**
* @param Organization $organization
* @param User $user
* @return \Doctrine\ORM\QueryBuilder
*/
public function getFindByOrganizationQueryBuilder(Organization $organization, User $user)
{
$nots = $this->_em
->createQueryBuilder()
->select('u.id')
->from('AppBundle:User\User', 'u', 'u.id')
->leftJoin('u.roles', 'r')
->where('r.role = ?1')
->orWhere('r.role = ?2')
->setParameter(1, 'ROLE_ADMIN')
->setParameter(2, 'ROLE_SUPER_ADMIN')
->getQuery()
->getResult()
;
$nots = array_keys($nots);
$builder = $this
->createQueryBuilder('u')
->leftJoin('u.roles', 'r')
->leftJoin('u.associates', 'a')
->leftJoin('a.organization', 'o')
->where('o = ?1')
->andWhere('u <> ?2')
->setParameter(1, $organization)
->setParameter(2, $user)
;
if (!empty($nots))
{
$builder = $builder
->andWhere($this->createQueryBuilder('u')->expr()->notIn('u.id', $nots));
}
return $builder;
}