[Drupal] How to use OR clause in hook_view_query_alter in Drupal 7

| | 1 min read

Sometimes we use Drupal view_query_alter to add or modify the view's where clause. To add a new WHERE clause we may use add_where property. Whenever we use an add_where, it will create a WHERE clause along with an AND condition. There will be some cases were we need to use OR instead of AND. So if you want to know more about how to use OR clause in hook_view_query_alter, read on to know more.

We can use db_or to add a new OR condition with add_where. For example see the sample code

function mymodule_views_query_alter(&$view, &$query) {
  if ('yourviewname' == $view->name && 'page' == $view->current_display) {
    $weight_parent = array(29,31);
    $or = db_or()
    ->condition('taxonomy_term_data_taxonomy_term_hierarchy.weight', 'NULL', 'IS')
    ->condition('taxonomy_term_data_node.weight', $weight_parent, 'IN');
    $query->add_where(1,$or);
  }
}

This will create an OR in among two WHERE clauses. Now you can enable 'Show the SQL query in view settings(admin/structure/views) then you can check the updated query at the bottom of view settings page(admin/structure/views/view/your_view_name).

"old query" AND ((taxonomy_term_data_taxonomy_term_hierarchy.weight IS 'NULL') OR (taxonomy_term_data_node.weight IN  ('29', '31')))

Similarly you can use db_and to add AND condition. Hope this helps someone out there. Thanks!