2017-06-15 87 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