7

I would like to convert the following UpdateQuery statement to work with multiple conditions by using OR instead of the default AND condition.

db_update('system')
  ->fields(array('status' => 1))
  ->condition('type', 'theme')
  ->condition('name', 'seven') // OR
  ->condition('name', 'rubik')
  ->execute();

Is it possible?

1 Answer 1

8

Drupal 7

Yes, it is possible by using db_or() as in the following example.

db_update('system')
  ->fields(array('status' => 1))
  ->condition('type', 'theme')
  ->condition(db_or()
    ->condition('name', 'seven')
    ->condition('name', 'rubik')
  )
  ->execute();

For db_select(), see the answers given in "OR" condition in db_select() and Nested OR and AND condition with db_select.

Drupal 8

You can still use db_or() as in Drupal 7, but it's deprecated in Drupal 8.0.x and removed in Drupal 9.0.0. Instead, a \Drupal\Core\Database\Query\Condition object should be created as in the following code, taken from BooleanOperator::queryOpBoolean().

if ($this->accept_null) {
  if ($query_operator === self::EQUAL) {
    $condition = (new Condition('OR'))
      ->condition($field, 0, $query_operator)
      ->isNull($field);
  }
  else {
    $condition = (new Condition('AND'))
      ->condition($field, 0, $query_operator)
      ->isNotNull($field);
  }
  $this->query->addWhere($this->options['group'], $condition);
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.