【问题标题】:How to use andWhere and orWhere in Doctrine?如何在 Doctrine 中使用 andWhere 和 orWhere?
【发布时间】:2012-02-24 02:11:24
【问题描述】:
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 中...?

【问题讨论】:

    标签: php sql doctrine


    【解决方案1】:

    这里缺少一件事:如果您有不同数量的元素想要组合成类似的东西

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

    不想自己组装 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);
    

    【讨论】:

    • 这个解决方案安全吗? SQL注入呢?
    • 不确定,这是在创建 DQL,而不是 SQL,但它可能是可能的。 @paul-attuck 指出了类似的东西。如果你想保持储蓄,我想它会像$qb->expr()->like('field', $qb->expr()->literal('%:val_i%')) 然后$qb->setParameter('val_<i>', $value) 但你很可能用这个搞砸了类似的声明并且没有得到你想要的。
    【解决方案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)
       ))
      ;
    

    这些是捷克学答案中提到的表达方式。

    【讨论】:

      【解决方案3】:
      $q->where("a = 1")
        ->andWhere("b = 1 OR b = 2")
        ->andWhere("c = 2 OR c = 2")
        ;
      

      【讨论】:

      • 那为什么不把它全部放在where()调用中呢?
      • 我不会对这种语法感到满意...如果您尝试迁移到某种病态的“SQL”,其中OR 将被|| 替换...这是如何工作的,当你需要使用b = ? OR b = ?
      • @Dems 是的,这当然是可能的。不过,这种方法更快。
      • @Vyktor:学说可以解决这个问题。这实际上是 DQL,而不是 SQL - Doctrine QL,它被转换为对您透明的有效的供应商特定 SQL。另外:andWhere("b=? OR b=?", array(1, 2)).
      • 我认为这应该是 $q->where("a = 1") ->andWhere("(b = 1 OR b = 2)") ->andWhere("(c = 2或 c = 2)");
      【解决方案4】:

      为什么不直接

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

      编辑:您也可以使用Expr class (Doctrine2)。

      【讨论】:

      • 问题是针对 1.2 的教义,您链接的文档针对的是 2.0。
      • @Maerlyn,好吧,这个问题没有doctrine-1.2 标签,所以我不能确定用户指的是哪一个——在这种情况下,我隐含地期待最新的一个。
      • 我的错误,不知道在教义2的查询构建器中有andWhere和orWhere。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-12
      • 2021-10-10
      • 2011-01-06
      • 2023-03-27
      • 1970-01-01
      相关资源
      最近更新 更多