Doctrine - DQL- 多个 OR 嵌套在一个封装的 AND 中
Doctrine - DQL- multiple ORs nested within one encapsulating AND
我找不到 DQL 的示例,这是半伪代码的样子:
Bring back invoices
- Where company id = 5
AND
(
->where('DATE(i.startPeriod) BETWEEN :startDate AND :endDate')
->orWhere('DATE(i.endPeriod) BETWEEN :startDate AND :endDate')
->orWhere(':startDate BETWEEN DATE(i.startPeriod) and DATE(i.endPeriod)')
->orWhere(':endDate BETWEEN DATE(i.startPeriod) and DATE(i.endPeriod)')
)
所以您有四个 OR 嵌套在一个封装的 AND 中。
有谁知道如何使用 Doctrine DQL 做到这一点?在一个巨大的 AND 中嵌套一堆 OR?
您需要将 Expr()
class 与查询构建器一起使用。
// $qb instanceof QueryBuilder
$qb->select('i')
->from('invoices', 'i')
->where('c.id = :cid')
->andWhere($qb->expr()->orX(
$qb->expr()->between('i.startPeriod',':startdate',':enddate'),
$qb->expr()->between('i.endPeriod',':startdate',':enddate'),
...
您可以在 the documentation 中阅读有关 Expr()
class 的更多信息。
编辑:
刚刚意识到您最初的问题是专门针对 DQL 提出的。您可以在 DQL 中使用括号来对事物进行分组,就像这样。
$query = $em->createQuery(
'SELECT i FROM Invoices i
WHERE c.id = :id
AND (
(i.startPeriod BETWEEN :startDate AND :endDate)
OR
(i.endPeriod BETWEEN :startDate AND :endDate)
OR
(:startDate BETWEEN i.startPeriod AND i.endPeriod)
OR
(:endDate BETWEEN i.startPeriod AND i.endPeriod)
) JOIN i.company c');
我找不到 DQL 的示例,这是半伪代码的样子:
Bring back invoices
- Where company id = 5
AND
(
->where('DATE(i.startPeriod) BETWEEN :startDate AND :endDate')
->orWhere('DATE(i.endPeriod) BETWEEN :startDate AND :endDate')
->orWhere(':startDate BETWEEN DATE(i.startPeriod) and DATE(i.endPeriod)')
->orWhere(':endDate BETWEEN DATE(i.startPeriod) and DATE(i.endPeriod)')
)
所以您有四个 OR 嵌套在一个封装的 AND 中。
有谁知道如何使用 Doctrine DQL 做到这一点?在一个巨大的 AND 中嵌套一堆 OR?
您需要将 Expr()
class 与查询构建器一起使用。
// $qb instanceof QueryBuilder
$qb->select('i')
->from('invoices', 'i')
->where('c.id = :cid')
->andWhere($qb->expr()->orX(
$qb->expr()->between('i.startPeriod',':startdate',':enddate'),
$qb->expr()->between('i.endPeriod',':startdate',':enddate'),
...
您可以在 the documentation 中阅读有关 Expr()
class 的更多信息。
编辑:
刚刚意识到您最初的问题是专门针对 DQL 提出的。您可以在 DQL 中使用括号来对事物进行分组,就像这样。
$query = $em->createQuery(
'SELECT i FROM Invoices i
WHERE c.id = :id
AND (
(i.startPeriod BETWEEN :startDate AND :endDate)
OR
(i.endPeriod BETWEEN :startDate AND :endDate)
OR
(:startDate BETWEEN i.startPeriod AND i.endPeriod)
OR
(:endDate BETWEEN i.startPeriod AND i.endPeriod)
) JOIN i.company c');