Upgrade Your Drupal Skills
We trained 1,000+ Drupal Developers over the last decade.
See Advanced Courses NAH, I know EnoughArbitrary "OR" SQL Queries
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.
Trackback URL for this post:
(2 votes)
More Quicktips
- 2 of 108
About Drupal Sun
Drupal Sun is an Evolving Web project. It allows you to:
- Do full-text search on all the articles in Drupal Planet (thanks to Apache Solr)
- Facet based on tags, author, or feed
- Flip through articles quickly (with j/k or arrow keys) to find what you're interested in
- View the entire article text inline, or in the context of the site where it was created
See the blog post at Evolving Web