如何在Doctrine中使用andWhere和orhere?

Pau*_*uck 65 php sql doctrine

WHERE a = 1 AND (b = 1 Or b = 2) AND (c = 1 OR c = 2)
Run Code Online (Sandbox Code Playgroud)

我怎么能在Doctrine中做到这一点?

$q->where("a = 1");
$q->andWhere("b = 1")
$q->orWhere("b = 2")
$q->andWhere("c = 1")
$q->orWhere("d = 2")
Run Code Online (Sandbox Code Playgroud)

这不正确......应该是:

$q->where("a = 1");
$q->andWhere("b = 1")
   $q->orWhere("b = 2")
$q->andWhere("c = 1")
   $q->orWhere("d = 2")
Run Code Online (Sandbox Code Playgroud)

但我怎么能做到呢?在Propel中是函数getNewCriterion,在Doctrine中......?

Mae*_*lyn 102

$q->where("a = 1")
  ->andWhere("b = 1 OR b = 2")
  ->andWhere("c = 2 OR c = 2")
  ;
Run Code Online (Sandbox Code Playgroud)

  • 那么为什么不把它全部放在`where()`调用中呢? (9认同)
  • @Vyktor:doctrine处理这个问题.这实际上是DQL,而不是SQL - Doctrine QL,它转换为对您有效的特定供应商特定SQL.另外:`和其中("b =?OR b =?",数组(1,2))`. (5认同)
  • 我不会对这种语法感到满意......如果你试图迁移到一些病态的"SQL",其中`OR`将被`||`替换...怎么样,当你需要使用`b =?或者b =?` (3认同)

Ser*_*nin 67

这是一个例子,适用于那些条件更复杂且使用Doctrine 2.*的人QueryBuilder:

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

这些是Czechnology答案中提到的表达.


Cze*_*ogy 12

为什么不呢

$q->where("a = 1");
$q->andWhere("b = 1 OR b = 2");
$q->andWhere("c = 1 OR d = 2");
Run Code Online (Sandbox Code Playgroud)

编辑:您也可以使用Expr类(Doctrine2).

  • @Maerlyn,好吧,问题没有`doctrine-1.2`标签,所以我无法确定用户意味着哪一个 - 在这种情况下我隐含地期望最新的一个. (4认同)

leb*_*cht 8

这里缺少一件事:如果您想将不同数量的元素放在一起,例如

WHERE [...] AND (field LIKE '%abc%' OR field LIKE '%def%')
Run Code Online (Sandbox Code Playgroud)

不想自己组装DQL字符串,可以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);
Run Code Online (Sandbox Code Playgroud)