How can i put condition in doctrine query builder

谁说胖子不能爱 提交于 2019-12-12 15:58:37

问题


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


回答1:


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);
}


来源:https://stackoverflow.com/questions/11965534/how-can-i-put-condition-in-doctrine-query-builder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!