Wednesday, July 17, 2013

SQL JOINS using Drupal db_select

Here's how to use Drupal's db_select function to perform a SQL INNER JOIN like below:

SELECT n.*, u.name FROM node n 
INNER JOIN users u on n.uid = u.uid
WHERE u.id = 3

Drupal db_select version:

$q = db_select('node', 'n');
$q->join('users', 'u', 'u.uid = n.uid');

$q->fields('n');
$q->fields('u', array('name'));

$q->condition('u.uid', 3);
  
$results = $q->execute();

No comments: