Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i put condition in doctrine query builder

I have this query

$qb->select('u')
           ->from('UserBundle:User', 'u')
           ->where('u.location = :identifier')
           ->orderBy('u.firstName', 'ASC')
           ->setParameter('identifier', 2);

I want that if $identifier is present then it should filter the results otherwise i get all the results like

$qb->select('u')
               ->from('UserBundle:User', 'u')
                       if($identifier)             
                       ->where('u.location = :identifier')
               ->orderBy('u.firstName', 'ASC')
                       if($identifier) 
               ->setParameter('identifier', 2);

Is it possible

like image 763
Mirage Avatar asked Dec 20 '22 17:12

Mirage


1 Answers

It is possible, you just have to restructure your code.

$qb->select('u')
           ->from('UserBundle:User', 'u')
           ->orderBy('u.firstName', 'ASC');
if($identifier) {
        $qb->where('u.location = :identifier')
           ->setParameter('identifier', 2);
}
like image 137
chiborg Avatar answered Jan 03 '23 10:01

chiborg