Doctrine orm Doctrine2简单where子句问题

Doctrine orm Doctrine2简单where子句问题,doctrine-orm,doctrine,Doctrine Orm,Doctrine,简而言之:我们不时地给一些用户送礼物。我有一个user表和一个具有多对多关系的gift表。我想获取所有没有收到特定礼物的用户 但是,下面的查询将返回所有用户以及他们收到的礼物,但不包括特定的礼物 $qb = $this->_em->createQueryBuilder(); $qb->select('u, g') ->from('Application\Entity\User', 'u') ->leftJoin('u.gifts',

简而言之:我们不时地给一些用户送礼物。我有一个
user
表和一个具有多对多关系的
gift
表。我想获取所有没有收到特定礼物的用户

但是,下面的查询将返回所有用户以及他们收到的礼物,但不包括特定的礼物

$qb = $this->_em->createQueryBuilder();
$qb->select('u, g')
        ->from('Application\Entity\User', 'u')
        ->leftJoin('u.gifts', 'g')
        ->where('g.id != = :giftId')
        ->setParameter('giftId', 2);

如果某个用户收到了特定的礼物,我想将该用户从结果集中排除。Doctrine2是否可以这样做?

您首先需要选择所有用户,然后排除那些已经拥有您的天赋的用户:

SELECT
    u
FROM
    Application\Entity\User u
WHERE
    u.id NOT IN(
        SELECT
            u2.id
        FROM
            Application\Entity\User u2
        JOIN
            u2.gifts g
        WHERE
            g.id = :giftId
    )
在中,它如下所示:

$qb1=$em->createQueryBuilder();
$qb2=$em->createQueryBuilder();
$qb2
->选择('u2')
->from('Application\Entity\User','u2')
->加入('u2.gives','g')
->andWhere($qb2->expr()->eq('g.id',':giftId');
$users=$qb1
->选择('u')
->from('Application\Entity\User','u')
->andWhere($qb1->expr->in($qb2->getDQL())
->setParameter('giftId',$giftId)
->getQuery()
->getResult();
另外,我个人不认为
QueryBuilder
适合这个用例,除非您有动态DQL。正如您所看到的,查询变得非常复杂,在某些时候,您甚至会回到
QueryBuilder\getDQL
,它构建DQL字符串并使
$qb2
的回收变得不可能。 普通DQL在这里工作得很好