简体   繁体   English

如何在 Doctrine 中使用 andWhere 和 orWhere?

[英]How to use andWhere and orWhere in Doctrine?

WHERE a = 1 AND (b = 1 Or b = 2) AND (c = 1 OR c = 2)

How can i make this in Doctrine?我怎样才能在 Doctrine 中做到这一点?

$q->where("a = 1");
$q->andWhere("b = 1")
$q->orWhere("b = 2")
$q->andWhere("c = 1")
$q->orWhere("d = 2")

this isnt correctly... Should be:这不正确......应该是:

$q->where("a = 1");
$q->andWhere("b = 1")
   $q->orWhere("b = 2")
$q->andWhere("c = 1")
   $q->orWhere("d = 2")

but how can i make it?但我怎样才能做到呢? In Propel is function getNewCriterion , and in Doctrine...?在 Propel 中是函数getNewCriterion ,在 Doctrine 中......?

$q->where("a = 1")
  ->andWhere("b = 1 OR b = 2")
  ->andWhere("c = 2 OR c = 2")
  ;

Here's an example for those who have more complicated conditions and using Doctrine 2.* with QueryBuilder :下面是一个例子,适用于那些条件更复杂并使用 Doctrine 2.* 和QueryBuilder

$qb->where('o.foo = 1')
   ->andWhere($qb->expr()->orX(
      $qb->expr()->eq('o.bar', 1),
      $qb->expr()->eq('o.bar', 2)
   ))
  ;

Those are expressions mentioned in Czechnology answer.这些是捷克语答案中提到的表达。

One thing missing here: if you have a varying number of elements that you want to put together to something like这里缺少一件事:如果您想将不同数量的元素组合在一起,例如

WHERE [...] AND (field LIKE '%abc%' OR field LIKE '%def%')

and dont want to assemble a DQL-String yourself, you can use the orX mentioned above like this:并且不想自己组装 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);

Why not just为什么不只是

$q->where("a = 1");
$q->andWhere("b = 1 OR b = 2");
$q->andWhere("c = 1 OR d = 2");

EDIT : You can also use the Expr class (Doctrine2).编辑:您还可以使用Expr 类(Doctrine2)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM