如何在Controller中划分查询?

时间:2014-09-03 17:17:49

标签: php symfony

如何在Controller中划分查询?

我有:

private function getPeoples($andWhere = null)
{
    $peoples = $this->getDoctrine()
                  ->getRepository('AcmeDemoBundle:People')
                  ->createQueryBuilder('p')
                  ->getQuery()
                  ->getResult();

    return $peoples;
}

这个工作正常,但我想为这个IF添加并且在哪里:

private function getPeoples($andWhere = null)
{
    $peoples = $this->getDoctrine()
                  ->getRepository('AcmeDemoBundle:People')
                  ->createQueryBuilder('p');
                if($andWhere == true){
                    $peoples->andWhere('p.test > 5');
                }

                  $peoples->getQuery()
                  ->getResult();

    return $peoples;
}

但这不起作用 - 对象不是null,但没有数据。为什么?在Symfony 1这个工作。我如何在Symfony2中制作它?

2 个答案:

答案 0 :(得分:1)

你走了:

$queryBuilder = $this->getDoctrine()->getManager()->createQueryBuilder();

$peopleQuery = $queryBuilder
    ->select('p')
    ->from('AcmeDemoBundle:People', 'p');

if ($andWhere === true) {
    $peopleQuery->andWhere('p.test > ?1');
    $peopleQuery->setParameter(1, 5);
}

$people = $peopleQuery->getQuery()->getResult();

顺便说一句,请不要将文字值插入DQL查询,使用位置参数和setParameter(),如上所示。

答案 1 :(得分:1)

嗯,你应该这样做:

private function getPeople($andWhere = null)
{
    $qb = $this->getDoctrine()->getManager()->getRepository('AcmeDemoBundle:People')
        ->createQueryBuilder('p');

    if($andWhere == true) {
        $qb->where('p.test > ?1')
           ->setParameter(1, 5)
    }

    $people = $qb->getQuery()->getResult();

    return $people;
}