[英]How to group more andWhere, orWhere in Doctrine
SELECT * FROM dg
WHERE
( a < 1 AND b > 1)
OR ( a > 1 AND (
(c = 3 AND B < 2)
or (c = 4 AND B < 5 ))
)
我不知道如何正確地集團更andWhere
和orWhere
。 我找到了一個更多AND組的例子,但沒有OR的例子。
對於exp。 WHERE a=1 AND (a>1 Or b=2) AND (a>1 OR c=2)
工作查詢是:
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中使用我的SELECT來創建Query Builder
?
對於和/或之類的,你可以鏈接的分組和層次結構and
的和or
“使用QueryBuilder的公司的S ->expr()
方法鏈接到->andX()
和->orX()
分別在您的QueryBuilder的實例。 您可以在此處查看更多信息: 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();
您也可以將orX()和andX()放入其他orX()和andX()中,並且可以在andX()和orX()中添加任意數量的條件,創建非常復雜的查詢。
玩得開心 :)
引用那個告訴我關於這個主題的明智話語的教程:
因此,即使存在orWhere()函數,也不要使用它 - 它可能會導致WTF時刻。
一般來說,即使選項存在,您也不會被迫使用它們。 在復雜的情況下,條款很難正確,控制括號的去向,可讀性等。
當我在這一點上時,我只是用你的例子放下一個帶正確括號等的那里:
->addWhere("
(a < 1 AND b > 1)
OR (
(a > 1) AND (
(c = 3 AND B < 2) OR
(c = 4 AND B < 5)
)
)
");
雖然這可能不是'正確的方法'(參見@TomDeRoo的答案),但至少我可以讀到最新情況。 只要知道你並不總是必須使用工具提供的所有東西。
您當然可以自由選擇您喜歡的任何解決方案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.