Symfony2/原则:findBy多个可以为NULL的查询


Symfony2 / Doctrine: findBy multiple queries that can be NULL

我有几个url查询,例如:

/page?type=train&category=others&location=germany
/page?type=car&category=others

我获取它们,并将它们放在变量中,以便用它们过滤数据库请求。

这就是我尝试的:

$item = $this->getDoctrine()
        ->getRepository('AppBundle:Item')
        ->findBy(array(
            'type' => $type,
            'category' => $category,
            'location' => $location
          ));

但正如你所能想象的,如果一个或多个变量为空,我不会得到任何结果。。。

我想查询数据库中的所有项目,并根据变量进行筛选,我该如何处理?

谢谢你的帮助!:)

请记住,您不必在querybuilder中创建findBy Criteria。相反,您可以在之前使用php的array_filter()创建它,它将删除所有空值:

$criteria = array_filter(array(
  'type' => 'search_type',
  'category' => null,
  'location' => 'search_location'
));
$item = $this->getDoctrine()
    ->getRepository('AppBundle:Item')
    ->findBy($criteria);