Symfony2 / Doctrine: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
          ));

但是你可以想象,如果一个或多个变量为空,我将得不到任何结果...

我想查询数据库中的所有项目并按变量过滤它们,我该如何处理?

感谢您的帮助! :)

请记住,您不必在查询构建器中创建 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);