在 symfony 中使用 querybuilder 创建一个特定的查询

create a specific query with querybuilder in symfony

我正在使用 symfony 3 开发应用程序,我想使用查询生成器创建自定义查询。
我有一个名为:Bien 的实体,它有很多地址。(地址是另一个实体)。所以我想获取 Bien 实体中不存在的所有地址。

我要生成的查询是:
select a.id from address a where a.id not in ( select b.address_id from bien b)

在我的 AddressRepository 中我这样做了 :

public function getAdressesByRueNotJoined($rue)
    {
        $qb2 = $this->createQueryBuilder('ab')
            ->from('BienBundle:Bien', 'bi');
        $qb = $this->createQueryBuilder('a');

        return
            $qb->where('a.rue = :rue')
                ->setParameter('rue', $rue)
                ->andWhere(
                    $qb->expr()->notIn('a', $qb2->getDQL())
                )
                ->getQuery()
                ->getResult();
    }

返回的查询是:

SELECT a0_.id AS id_0, a0_.name AS name_1, a0_.rue_id AS rue_id_2 FROM adresse a0_ WHERE a0_.rue_id = ? AND a0_.id NOT IN (SELECT a1_.id FROM adresse a1_, bien b2_)

我该如何解决?

看起来你的整个请求都是错误的,如果 Bien 与 Adresse 有一对多关系,你应该使用连接通过 Rue 查询你的 Biens

$qb = $this
    ->createQueryBuilder('b')
    ->select('b.id')
    ->from('BienBundle:Bien b')
    ->leftJoin('b.addresses' 'a' )
    ->where('a.rue = :rue')
    ->setParameter('rue', $rue)
    ->getQuery()
    ->getResult()
;

在 $qb2 中我添加了这样的身份

$qb2 = $this->createQueryBuilder('ad')
            ->from('SBC\BienBundle\Entity\Bien', 'bi')
            ->select('IDENTITY(bi.address)');

但我不知道这是什么意思