SELECT * FROM dg
WHERE
( a < 1 AND b > 1)
OR ( a > 1 AND (
(c = 3 AND B < 2)
or (c = 4 AND B < 5 ))
)
我不确定如何正确分组更多和哪些和哪些.我找到了一个更多AND组的例子,但没有OR的例子.
对于exp.其中a = 1 AND(a> 1或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来创建查询生成器?
解决方法:
对于or和/和之类的分组和层次结构,您可以使用querybuilder的 – > expr()方法链接和/或分别链接到您的QueryBuilder实例上的 – > andX()和 – > orX().您可以在此处查看更多信息: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()中添加任意数量的条件,创建非常复杂的查询.
玩得开心 :)