如何在Doctrine中使用conditionType'ON'?

问题描述 投票:0回答:1

我对准则ON有疑问。我读过here

现在在原则2中,我从未见过可以使用ON的情况。实际上,使用ON总是会导致出现异常,提示您应该使用与。

但是我需要重新定义加入条件。这是我的查询:

$qb = $this->createQueryBuilder('fu');
$qb
    ->addSelect('cra')
    ->innerJoin('fu.chatRoomAdmins', 'cra')
    ->where('cra.operator = :operatorId')
    ->setParameter('operatorId', $operatorId);
$foreignUsers = $qb->getQuery()->getResult();

这是(重要部分)生成的sql查询(我将表的名称更改为更具可读性):

SELECT *
FROM   fu
       INNER JOIN cra
               ON fu.id = cra.operator_id
WHERE  ( cra.operator_id = 'an_id');

但是我需要将ON条件更改为此:ON fu.id = cra.operator_id OR cra.operator_id IS NULL

如果我使用这样的WITH条件:

$qb
//..
    ->innerJoin('fu.chatRoomAdmins', 'cra', 'WITH', 'cra.operator IS NULL')
//..
$foreignUsers = $qb->getQuery()->getResult();

它像这样更改我的查询:

SELECT *
FROM   fu
       INNER JOIN cra
               ON fu.id = cra.operator_id 
                  AND ( cra.operator_id IS NULL ) 
WHERE  ( cra.operator_id = 'an_id' ); 

但是我想要此ON条件:ON fu.id = cra.operator_id OR ( cra.operator_id IS NULL )

这就是为什么我尝试在我的queryBuilder中用WITH替换ON的原因:

$qb
//..
    ->innerJoin('fu.chatRoomAdmins', 'cra', 'ON', 'cra.operator IS NULL')
//..
$foreignUsers = $qb->getQuery()->getResult();

但是现在我得到一个错误:Expected end of string, got 'ON'(我正在使用symfony 4)

您是否知道一种满足此ON条件的方法:ON fu.id = cra.operator_id OR ( cra.operator_id IS NULL )

doctrine-orm doctrine symfony4 doctrine-query
1个回答
0
投票

我找到了一种使用leftJoin的方法:

$qb = $this->createQueryBuilder('fu');
$qb
    ->addSelect('cra')
    ->leftJoin('fu.chatRoomAdmins', 'cra')
    ->where('cra.operator = :operatorId OR cra.operator IS NULL');
$foreignUsers = $qb->getQuery()->getResult();

给出此SQL:

SELECT *
FROM   fu 
       LEFT JOIN cra
              ON fu.id = cra.operator_id 
WHERE  ( cra.operator_id = 'an_id' 
          OR cra.operator_id IS NULL ); 
© www.soinside.com 2019 - 2024. All rights reserved.