在Doctrine中是否有正确的方法将'OR'嵌套在where子句中?

时间:2018-06-01 11:34:13

标签: symfony doctrine-orm

我有一个查询,如果他们有一个结束日期并且没有完成产生所需结果的某些工作:

真实代码

$this->createQueryBuilder('j')
                ->where('j.completed = :false OR j.completed is NULL')
                ->andWhere('j.has_due_date = :true')
                ->andWhere('j.has_due_date = :true')
                ->setParameters( array(
                    'false' => FALSE,
                    'true' => TRUE
                ) )
                ->orderBy('j.due_date', 'asc')
                ->getQuery();

结果

SELECT j FROM App\Entity\Jobs j 
    WHERE (
        j.completed = :false 
        OR j.completed is NULL
    ) 
    AND j.has_due_date = :true 
    ORDER BY j.due_date ASC

我想要遵循DQL最佳做法,感觉还有另一种方式或写这个,并且在WHERE变体上每次调用只有一个->where子句{{1 },andWhere()

在我看来它是这样的,但我找不到任何东西来确认它:

伪代码

orWhere()

主要问题是:

  • 有没有办法以第二种方式做到这一点?
  • 我不必要地过度复杂化了什么?
  • 如果有第二种方法如上所述,第一种说法是有效的,那为什么重要呢?

2 个答案:

答案 0 :(得分:0)

正如<html> <head> <script> function Consolify() { var firstMethod = document.getElementById('name').value; console.log('firstMethod = ', firstMethod); var secondMethod = document.getElementById('name'); console.log('secondMethod = ', secondMethod.value); console.log('thirdMethod = ', document.getElementById('name').value); } </script> </head> <body> <input type="text" id="name" placeholder="username"> <button onclick="Consolify()">Consolify</button> </body> </html>最佳实践的官方文档中所述,正确的方法是使用辅助方法QueryBuilder以及QueryBuilder::expr()帮助程序类。 High level API methods

即:

Doctrine\ORM\Query\Expr

答案 1 :(得分:0)

使用查询构建器应该更容易,更容易理解

    public function someFunction()
    {
        $qb = $this->createQueryBuilder('j');

        $orX = $qb->expr()->orX();
        $andX = $qb->expr()->andX();

        $orX->add($qb->expr()->eq('j.completed', $qb->expr()->literal(false)));
        $orX->add($qb->expr()->isNull('j.completed'));

        $andX->add($qb->expr()->eq('j.has_due_date', $qb->expr()->literal(true)));

        $qb->andWhere($orX, $andX)
            ->orderBy('j.due_date', 'asc')
            ->getQuery()
            ->getResult();
    }