使用方法GET搜索多个条件

时间:2014-12-20 20:14:49

标签: php symfony doctrine-orm

我创建了一个使用多条件进行搜索的代码,但只有在表单中填写所有字段时才有效,如果字段为空,则查询返回零结果。我该如何解决这个问题?

控制器:

public function listSearchAction($page, Request $request)
{

    if ($request->getMethod() == 'GET') {

    $em = $this->getDoctrine()->getManager();

    $paginator  = $this->get('knp_paginator');


    $name = $request->query->get('name');
    $city = $request->query->get('city');

    $qb = $em->getRepository('ProjectAgenceBundle:Agence')->getListSearchAgencesFrontend($name, $city); 

    $pagination = $paginator->paginate(
    $qb,
    $request->query->get('page', $page),10);

    }


    return $this->render('ProjectFrontendBundle:Agence:agence-search-list-view.html.twig',array(
    'pagination' => $pagination,
    'mode'=> $mode,
    ));
}    

存储库:

public function getListSearchAgencesFrontend($name, $city)
{
    $qb = $this->createQueryBuilder('a')
        ->leftJoin('a.logo', 'l')
        ->addSelect('l')
        ->Where('a.enabled = 1')
        ->andWhere('a.city = :city')
        ->setParameter('city', $city)
        ->andWhere('a.name LIKE :name')
        ->setParameter('name', '%'.$name.'%');

    return $qb;

}

form.twig

<form action="{{ path('frontend_agences_list_search') }}" method="get" name="left_search">
               <div class="form-group">
                    <label>Name</label>
                          {{ form_widget(left_form_search.name) }}
               </div>

               <div class="form-group">
                    <label>City</label>
                 <div class="selector">
                    {{ form_widget(left_form_search.city) }}
                 </div>
               </div>
               {{ form_rest(left_form_search) }}
               <br />
              <button type="submit" class="btn-medium icon-check uppercase full-width">Search</button>
              </form>

1 个答案:

答案 0 :(得分:4)

在向查询添加条件之前,请确保您的参数不为空。

public function getListSearchAgencesFrontend($name = NULL, $city = NULL)
{
    $qb = $this->createQueryBuilder('a')
        ->leftJoin('a.logo', 'l')
        ->addSelect('l')
        ->Where('a.enabled = 1');
    if (!empty($city)) {
        $qb->andWhere('a.city = :city')
            ->setParameter('city', $city);
    }
    if (!empty($name)) {
        $qb->andWhere('a.name LIKE :name')
            ->setParameter('name', '%'.$name.'%');
    }

    return $qb;

}

已更新:使用!empty()而不是!== NULL