Reputation: 97
How to divide query in Controller?
I have:
private function getPeoples($andWhere = null)
{
$peoples = $this->getDoctrine()
->getRepository('AcmeDemoBundle:People')
->createQueryBuilder('p')
->getQuery()
->getResult();
return $peoples;
}
This working ok, but i would like add for this IF and andWhere:
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;
}
but this not working - object is not null, but not have data. Why? In Symfony 1 this working. How can i make it in Symfony2?
Upvotes: 0
Views: 108
Reputation: 4081
Well, you should do something like this:
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;
}
Upvotes: 1
Reputation: 13127
Here you go:
$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();
By the way, please do not insert literal values into a DQL query, use positional parameters together with setParameter()
, as seen above.
Upvotes: 1