Kikimac
Kikimac

Reputation: 179

Doctrine2 Symfony2 how to ignore NULL in query builder?

I have a route with may or may not contain values, and wish to query Doctrine based on that,

 /**
 * @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';
}

So for instance:

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

Would query for Books with a region of England , a town of London and a road of Streetroad.

A route of:

http://localhost/book

Should query for Books, and return all books.

Instead, its currently just querinyg :

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

Which makes sense, but what is the best way of getting the results I require? Or do I need to revert DQL?

Upvotes: 0

Views: 653

Answers (2)

Nicolai Fröhlich
Nicolai Fröhlich

Reputation: 52473

You can do something like this:

// ...

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

// ...

    ->findBy($filters),

// ...   

or in short form with array filter:

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

Upvotes: 0

Arnaud Le Blanc
Arnaud Le Blanc

Reputation: 99879

Use array_filter to remove NULL values from your array:

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

Upvotes: 2

Related Questions