带有可选参数的Dql查询

时间:2016-10-26 09:45:31

标签: mysql symfony doctrine-orm doctrine

我想知道如何使用可选参数进行DQL查询例如:

public function getUsers($city, $sex, $age)
    {
        $qb = $this->getEntityManager()->createQueryBuilder()
            ->select('u')
            ->where('u.sex = :sex')
            ->andWhere('u.city = :city')
            ->andWhere('u.age = :age')
        ->setParameter(':city', $city);
        ->setParameter(':sex', $sex);
        ->setParameter(':age', $age);
        $query = $qb->getQuery();
        $result = $query->getResult();

    }

如果没有定义其中一个参数(= NULL)怎么办?

2 个答案:

答案 0 :(得分:1)

在这种情况下,设置为NULL的参数可能有意义,因为即使它不是标准的,您也可以表示IS NULL条件(仅为了示例){{1其中u.age = :ageage(我建议read this topic}

所以,很明显你需要自己检查它(如果你打算将它们作为可选项)并且如果该参数是NULL则不添加条件(以及参数绑定)。

请注意,如果NULL(列为第一个参数)为空,则应在sex条件下对where使用andWhere,依此类推。

答案 1 :(得分:1)

public function getUsers($city, $sex, $age)
{
    $qb = $this->getEntityManager()->createQueryBuilder()
        ->select('u')
        ->from('User', 'u');

    if (isset($sex)) {
        $qb->andWhere('u.sex = :sex')
           ->setParameter(':sex', $sex);
    }

    if (isset($city)) {
        $qb->andWhere('u.city = :city')
           ->setParameter(':city', $city);
    }

    if (isset($sex)) {
        $qb->andWhere('u.sex = :sex')
           ->setParameter(':age', $age);
    }

    return $qb->getQuery()->getResult();    
}