0

我有一条可能包含或不包含值的路线,并希望基于此查询 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

将查询具有 England 地区、London 镇和 Streetroad 道路的 Books。

一条路线:

http://localhost/book

应该查询书籍,并返回所有书籍。

相反,它目前只是 querinyg :

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

这是有道理的,但是获得我需要的结果的最佳方法是什么?还是我需要恢复 DQL?

4

2 回答 2

2

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

->findBy(array_filter(array(
      'productType' => $productType,
      'region' => $region,
      'town' => $town,            
      'road' => $road               
), 'is_null'),
于 2013-05-23T17:28:08.323 回答
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'
      )
  )
于 2013-05-23T17:08:35.990 回答