具有多个 AND OR 条件的学说

Doctrine withh multiple AND OR conditions

我正在尝试将以下查询转换为学说

SELECT E.id,E.publication_status FROM event AS E INNER JOIN event AS ESP ON  ESP.id = E.super_parent_id 
INNER JOIN event_details AS ESPD ON ESPD.event_id = ESP.id 
INNER JOIN subscription_settings AS ES WHERE ES.event_id = E.id

AND (
(ES.subscription_start_mode="PUBLICATION" AND ESP.publication_planned_from_date >= '2020-02-04 05:30:51' AND ESP.publication_planned_from_date <= '2020-02-04 05:35:51')
OR
( ES.subscription_start_mode="SCHEDULED" AND ES.subscription_scheduled_start_date >= '2020-02-04 05:30:51' AND ES.subscription_scheduled_start_date <= '2020-02-04 05:35:51')
)

AND E.is_archived = 0 AND E.is_deleted = 0

在学说中尝试过的代码

this->createQueryBuilder("E")
         ->select("E.id,E.publicationStatus,E.isArchived,E.isCancelled")
         ->innerJoin('MYBundle:Event', 'ESP', 'WITH', 'ESP.id = E.superParent')
         ->innerJoin('MYBundle:EventDetails', 'ESPD', 'WITH', 'ESPD.event = ESP.id')
         ->innerJoin("MYBundle:SubscriptionSettings", "ES", "WHERE", "ES.event = E.id")
         ->andWhere("((ES.subscriptionStartMode='PUBLICATION' AND ESP.publicationPlannedFromDate >= :from AND  ESP.publicationPlannedFromDate <= :to) OR (ES.subscriptionStartMode='SCHEDULED' AND ES.subscriptionScheduledStarDate >= :from AND S.subscriptionScheduledStarDate <= :to))")
         ->setParameter('from', $fDate)->setParameter('to', $tDate);

这给出了错误

Syntax Error] line 0, col 336: Error: Expected end of string, got 'WHERE

首先,andWhere通常在where之后。

其次,WHERE 谓词在连接条件中是不允许的,只要它保留了 SQL 的一部分。使用 WITH 代替:

->innerJoin("MYBundle:SubscriptionSettings", "ES", "WHERE", "ES.event = E.id")

第三,你可以利用andXorX

$qb = this->createQueryBuilder("E");

$qb
    ->select(...)
    ->innerJoin(...)
    ->where(
        $qb->expr()->orX(
           $qb->expr()->andX(
               $qb->expr()->eq('ES.subscriptionStartMode', ':modePlan'),
               $qb->expr()->gt('ESP.publicationPlannedFromDate', ':from'),
               $qb->expr()->lte('ESP.publicationPlannedFromDate', ':to'),
           ),

           $qb->expr()->andX(
               $qb->expr()->eq('ES.subscriptionStartMode', ':modeSchedule'),
               $qb->expr()->gte('ESP.subscriptionScheduledStarDate', ':from'),
               $qb->expr()->lte('ESP.subscriptionScheduledStarDate', ':to'),
           ),
        )
    )
    ->setParameter('modePlan', 'PUBLICATION')
    ->setParameter('modeSchedule', 'SCHEDULED')
    ->setParameter('from', ...)
    ->setParameter('to', ...);

请注意,即使是静态的,也最好通过setParameter设置参数。

您可以根据需要混合使用 orX 和 andX 运算符。在 official docs

中查看有关 DQL 运算符的更多信息