php 如何在 Doctrine 中使用 andWhere 和 orWhere?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9095113/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 06:08:47  来源:igfitidea点击:

How to use andWhere and orWhere in Doctrine?

phpsqldoctrine

提问by Paul Attuck

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 中......?

回答by Maerlyn

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

回答by Serge Kvashnin

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.

这些是捷克语答案中提到的表达。

回答by Czechnology

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)。

回答by leberknecht

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 orXmentioned above like this:

并且不想自己组装 DQL-String,您可以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);