[英]How to use andWhere and orWhere in Doctrine?
WHERE a = 1 AND (b = 1 Or b = 2) AND (c = 1 OR c = 2)
我怎樣才能在 Doctrine 中做到這一點?
$q->where("a = 1");
$q->andWhere("b = 1")
$q->orWhere("b = 2")
$q->andWhere("c = 1")
$q->orWhere("d = 2")
這不正確......應該是:
$q->where("a = 1");
$q->andWhere("b = 1")
$q->orWhere("b = 2")
$q->andWhere("c = 1")
$q->orWhere("d = 2")
但我怎樣才能做到呢? 在 Propel 中是函數getNewCriterion ,在 Doctrine 中......?
$q->where("a = 1")
->andWhere("b = 1 OR b = 2")
->andWhere("c = 2 OR c = 2")
;
下面是一個例子,適用於那些條件更復雜並使用 Doctrine 2.* 和QueryBuilder
:
$qb->where('o.foo = 1')
->andWhere($qb->expr()->orX(
$qb->expr()->eq('o.bar', 1),
$qb->expr()->eq('o.bar', 2)
))
;
這些是捷克語答案中提到的表達。
這里缺少一件事:如果您想將不同數量的元素組合在一起,例如
WHERE [...] AND (field LIKE '%abc%' OR field LIKE '%def%')
並且不想自己組裝 DQL-String,您可以像這樣使用orX
提到的orX
:
$patterns = ['abc', 'def'];
$orStatements = $qb->expr()->orX();
foreach ($patterns as $pattern) {
$orStatements->add(
$qb->expr()->like('field', $qb->expr()->literal('%' . $pattern . '%'))
);
}
$qb->andWhere($orStatements);
為什么不只是
$q->where("a = 1");
$q->andWhere("b = 1 OR b = 2");
$q->andWhere("c = 1 OR d = 2");
編輯:您還可以使用Expr 類(Doctrine2)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.