Arbitrary "OR" SQL Queries

Published March 25, 2013

I was working on a Drupal migration project today using the Migrate module where I needed to import only select user roles from the source (Drupal 6) database.

The Migrate module allows for a custom query to select only the user roles that need to be imported. In my case, the two roles I wanted to import had role IDs of 4 and 6. So, how do I write a query using the Drupal Database API to do this? Turns out there's a pretty elegant answer. Rather than writing something like:

SELECT * FROM role r WHERE rid=4 OR rid=6;

The proper way of writing the select query is:

$query = parent::query();
$ored = db_or();
$ored
->condition('rid', 4)
->condition('rid', 6);
$query->condition($ored);

Note the elegant "db_or()" function that returns a DatabaseCondition object. Add the two conditions to this object, and they're automagically "or"ed.

I discovered all this via this nice blog post by Rahul Singla.

Comments

Umm, doesn't
$query->condition('rid', array(4,6), 'IN');
do it?

But yes, the db_and and db_or methods are very useful.

Love your podcasts!

Submitted by Guest (not verified) on Mon, 03/25/2013 - 23:55

Author comment

Yep, "$query->condition('rid', array(4,6), 'IN');" will work as well, but for some reason, I find the db_or method a bit more elegant.

Thanks,
-mike

Submitted by ultimike on Tue, 03/26/2013 - 07:17

In reply to by Guest (not verified)

Sign up to receive email notifications of whenever we publish a new blog post or quicktip!

Name
CAPTCHA