Doctrine2 Symfony2如何在查询生成器中忽略NULL?

时间:2013-05-23 16:08:54

标签: php symfony doctrine-orm

我有一条路线,可能包含或不包含值,并希望根据该路径查询Doctrine,

 /**
 * @Route("/{productType}/{region}/{town}/{road}", name="product_type" , defaults={"productType" = null , "region" = null , "town" = null , "road" = null  })
 * @Template()
 */
public function productTypeAction($productType, $region , $town , $road)
{       
    $properties = $this->getDoctrine()
    ->getRepository('MyBundle:Product')
    ->findBy(
    array('productType' => $productType,
          'region' => $region,
          'town' => $town,            
          'road' => $road               
    ),
    array('id' => 'ASC'));    



    return 'mytwig';
}

例如:

http://localhost/book/england/london/streetroad

将查询与英格兰地区,伦敦小镇和Streetroad之路的书籍。

路线:

http://localhost/book

应查询图书,并返回所有图书。

相反,它目前只是querinyg:

t0.productid = ? 
  AND t0.region IS NULL 
  AND t0.town IS NULL      
  AND t0.road IS NULL 

哪个有道理,但获得我需要的结果的最佳方式是什么?或者我是否需要还原DQL?

2 个答案:

答案 0 :(得分:2)

使用array_filter从数组中删除NULL值:

->findBy(array_filter(array(
      'productType' => $productType,
      'region' => $region,
      'town' => $town,            
      'road' => $road               
), 'is_null'),

答案 1 :(得分:0)

您可以这样做:

// ...

$filters =  array(
      'productType' => $productType,
      'region'      => $region,
      'town'        => $town,            
      'road'        => $road               
);
foreach ( $filters as $key => $value) {
    if ($filters[$key] === null) { 
        unset($filters[$key]); 
    }
}

// ...

    ->findBy($filters),

// ...   

或带有数组过滤器的简短形式:

->findBy(
      array_filter(
          array(
              'productType' => $productType,
              'region' => $region,
              'town' => $town,            
              'road' => $road               
           ),
           'is_null'
      )
  )