如何分组更多和哪​​些,或者在Doctrine中

Gre*_*ene 3 php sql symfony doctrine-orm

SELECT * FROM dg
WHERE 
     ( a < 1 AND b > 1)
  OR ( a > 1 AND ( 
                     (c = 3 AND B < 2) 
                  or (c = 4 AND B < 5 ))
     )
Run Code Online (Sandbox Code Playgroud)

我不确定如何正确分组更多andWhereorWhere.我找到了一个更多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()
        ;
}
Run Code Online (Sandbox Code Playgroud)

如何在Doctrine2中使用我的SELECT来创建Query Builder

Tom*_*Roo 8

对于分组和层次结构和/或之类的,你可以链接and的和or的使用的QueryBuilder的->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();
Run Code Online (Sandbox Code Playgroud)

您也可以将orX()和andX()放入其他orX()和andX()中,并且可以在andX()和orX()中添加任意数量的条件,创建非常复杂的查询.

玩得开心 :)

  • 我编辑了代码以尝试澄清。我不得不假设很多,因为您提供的代码并不能准确地告诉您要检索哪个实体,但您应该能够通过类比获得一个示例。请查看我为 Doctrine 手册提供的链接;关于如何实现你想要做的事情非常清楚。 (2认同)