1

Short and Simple: From time to time we send gifts to some of our users. I have a user table and a gift table with a many-to-many relationship. I want to fetch all users which did NOT receive a particular gift.

The following query however returns me all users and the gifts they've received, with the particular gift excluded.

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

If a user received a particular gift, I want to exclude that user from the result set. Is this possible with Doctrine2?

4

1 回答 1

0

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

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
    )

API中,它如下所示:QueryBuilder

$qb1 = $em->createQueryBuilder();
$qb2 = $em->createQueryBuilder();

$qb2
    ->select('u2')
    ->from('Application\Entity\User', 'u2')
    ->join('u2.gifts', 'g')
    ->andWhere($qb2->expr()->eq('g.id', ':giftId');

$users = $qb1
    ->select('u')
    ->from('Application\Entity\User', 'u')
    ->andWhere($qb1->expr->in($qb2->getDQL())
    ->setParameter('giftId', $giftId)
    ->getQuery()
    ->getResult();

另外,我个人认为它不QueryBuilder适合这个用例,除非你有动态 DQL。如您所见,查询变得相当复杂,有时您甚至会退回到QueryBuilder#getDQL,这会构建 DQL 字符串并使回收$qb2变得不可能。普通的 DQL 在这里工作得很好。

于 2013-03-16T01:14:07.903 回答