2017-06-15 41 views
1
SELECT * FROM dg 
WHERE 
    (a < 1 AND b > 1) 
    OR (a > 1 AND ( 
        (c = 3 AND B < 2) 
        or (c = 4 AND B < 5)) 
    ) 

我不知道如何正确地集团更andWhereorWhere。我发现了一个更多的例子,但不是OR的例子。
For exp。 WHERE a=1 AND (a>1 Or b=2) AND (a>1 OR c=2)工作查询:如何组更andWhere,orWhere教义

public function myQuery() 
{ 
    return $this->createQueryBuilder('dg') 
       ->where("a = 1") 
       ->andWhere("a > 1 OR b = 2") 
       ->andWhere("a > 1 OR c = 3") 
       ->getQuery() 
       ->getResult() 
     ; 
} 

我如何使用我的Doctrine2选择创建Query Builder

回答

5

对于分组和层次结构和/或之类的,你可以分别在您的QueryBuilder的实例链接使用的QueryBuilder的->expr()方法链接到->andX()->orX()and的和or的。您可以在这里获得更多信息:http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/query-builder.html#the-expr-class

基本上你会得到类似下面的翻译你的第二个声明:

// In this example I'll be assuming that 'dg' is an entity 
// and that 'a', 'b' and 'c' are its attributes 
// since, remember, Doctrine is designed specifically for using entities 
// and make abstraction of the whole table model in your database 

// First we'll create your QueryBuilder instance $qb 
$qb = $this->createQueryBuilder('dg'); 

// Then we add our statements to the QueryBuilder instance 
$qb 
    ->where($qb->eq('dg.a', 1)) 
    ->andWhere($qb->expr()->orX(
     $qb->expr()->gt('dg.a', 1), 
     $qb->expr()->eq('dg.b', 2) 
    )) 
    ->andWhere($qb->expr()->orX(
     $qb->expr()->gt('dg.a', 1), 
     $qb->expr()->eq('dg.c', 3) 
    )) 
; 

// Now you can use the QueryBuilder instance to, for instance, 
// have it do getResult (which in this case will return an array of 'dg' entities) 
return $qb->getQuery()->getResult(); 

你可以把或X()的和和X()的成其他orX()和andX()也是如此,你可以在你的orX()和orX()中添加任意数量的条件来创建非常复杂的查询。

玩得开心:)

+0

运行时我收到错误'未定义的变量qb'。你能举例说明吗? – Grene

+1

我编辑了代码来尝试和澄清。我不得不假设很多,因为你提供的代码并不完全知道你想要检索哪个实体,但是你应该能够通过类比得到一个例子。请检查我为“学说”手册提供的链接;关于如何实现你想要做的事情非常清楚。 –

+0

谢谢** Tom De Roo **求助 – Grene

1

要从告诉我明智的话关于这个主题的教程引用:

因此,即使有一个orWhere()函数,不使用它 - 它可以导致WTF时刻。

总的来说,即使选项存在,您也不会被迫使用它们。在复杂的情况下,很难得到正确的结果,控制括号的位置,可读性等。

当我在这一点上我刚放下的andWhere用正确的括号等像你的例子:

->addWhere(" 
    (a < 1 AND b > 1) 
    OR (
     (a > 1) AND (
      (c = 3 AND B < 2) OR 
      (c = 4 AND B < 5) 
     ) 
    ) 
"); 

虽然这可能不是“正确的方式”(请参阅​​从@答案TomDeRoo),但至少我可以读取正在发生的事情。只要知道你并不总是必须使用工具提供的所有东西。

你当然可以自由选择你喜欢的任何解决方案。

+0

感谢您的建议 – Grene