Nested OR , AND conditions in drupal query builder

Nested OR , AND conditions in drupal query builder

11 years ago, July 12, 2013
Reading time: 2 mins
Generally in Drupal query builder, we can chain condition() method to add AND conditions to the query we are building.
Which will create a query something like 
WHERE Condition1 AND Condition2 AND Condition3	
by following code:
<?php 

$query
  ->condition(Condition1)
  ->condition(Condition2)
  ->condition(Condition3); 

?>
 
Now If we want OR,
<?php

$query
  ->condition(
      db_or()
        ->condition(Condition1)
        ->condition(Condition2)
        ->condition(Condition3)
  );
  
?>
If we want to nest OR inside AND,
//something like 
WHERE (Condition1 OR Condition2) AND (Condition3 OR Condition4)	
You can do:
<?php
$query
  ->condition(
    db_or()
      ->condition(Condition1)
      ->condition(Condition2)
  );

$query
  ->condition(
    db_or()
      ->condition(Condition3)
      ->condition(Condition4)
  );
If we want to nest AND inside OR,
something like
WHERE (Condition1 AND Condition2) OR (Condition3 AND Condition4)
You can do:
<?php

$query
  ->condition(
      db_or()
        ->condition(
            db_and()
              ->condition(Condition1)
              ->condition(Condition2)
        )
        ->condition(
            db_and()
              ->condition(Condition3)
              ->condition(Condition4)
        )
  );

Previous
Kathmandu Kora Cycling Challenge 2014 #kora14
Next
Chain Animation function using deffer / promise in jquery
© 2024 Anil Maharjan