如果空白字段,请使用Doctrine进行搜索

时间:2015-02-23 06:12:02

标签: symfony doctrine-orm

我为我的多次搜索编写了一个DQL查询,如果我指定了所有字段,但是如果我将其中一个字段留空,它将无法显示结果

          $query = $em->createQuery
          ('SELECT d FROM EntityBundle:Doctor d WHERE d.name =:name AND d.degree =:degree AND d.area = :area_id AND d.sex = :sex AND
           (

                 ( YEAR(d.dob)  BETWEEN :d2 AND :d1 ) OR
                 ( YEAR(d.dob)  BETWEEN :e2 AND :e1 ) OR
                 ( YEAR(d.dob)  BETWEEN :f2 AND :f1 )

            )'          )

           ->setParameter('name', $name)
           ->setParameter('degree', $degree)
            ->setParameter('area_id', $area)
            ->setParameter('sex', $sex)
            ->setParameter('d1', $this->p1)
            ->setParameter('d2', $this->p2)
            ->setParameter('e1', $this->q1)
            ->setParameter('e2', $this->q2)
            ->setParameter('f1', $this->r1)
            ->setParameter('f2', $this->r2)

          ->getResult();

我试过setParameter('name',(is_null($ name)?“IS NULL”:$ name))但是还是没有运气..

1 个答案:

答案 0 :(得分:1)

您可以使用QueryBuilder而不是DQL

$qb = $qb->select('d');
if($name !== null) {
     $qb = $qb->where('d.name = :name')->setParameter(...);
}
...
$qb->getQuery()->getResult();