18.10.2016 Views

Drupal 7 Module Development

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Database Access<br />

Dynamic queries<br />

Although most SELECT queries are static, at times we will need a more flexible<br />

query. That could be because the query itself may change depending on incoming<br />

user data, because we want to allow other modules to modify our query before<br />

it is executed, or we want to take advantage of some database feature that is<br />

implemented differently on different databases. For these cases, <strong>Drupal</strong> provides<br />

a mechanism for building dynamic queries using a robust query builder.<br />

To start, we create a new query object with db_select():<br />

$query = db_select('node', 'n');<br />

The first parameter is the name of the base table of the query and the second is the<br />

alias we want to use for it. We then call additional methods on the $query object in<br />

order to build up the query logic we want to create dynamically. For example:<br />

$query = db_select('node', 'n');<br />

$query->fields('n', array('nid, title'));<br />

$u_alias = $query->innerJoin('users' ,'u', '%alias.uid = n.uid');<br />

$query->addField($u_alias, 'name', 'username');<br />

$query->condition("{$u_alias}.name", 'Bob');<br />

$query->condition('n.created', REQUEST_TIME - 604800, '>=');<br />

$query->orderBy('n.created', 'DESC');<br />

$query->range(0, 5);<br />

$query->addTag('node_access');<br />

$result = $query->execute();<br />

The fields() method tells the query to select the fields in the second parameter<br />

from the table in the first parameter. In this case, as of line 2, our query would<br />

effectively read:<br />

SELECT n.nid AS nid, n.title AS title FROM {node} n<br />

Note that the curly braces are added for us automatically. Also note that aliases are<br />

created for every field. If we want to specify an alternate alias, we need to use the<br />

addField() method for that one field. We'll see more on that shortly. We can also<br />

join against other tables using the innerJoin(), leftJoin(), and rightJoin()<br />

methods. There is also join(), which is an alias of innerJoin(). The join()<br />

methods take the table to join against, its alias, and the join conditions as parameters<br />

in the form of an SQL fragment. Note that in this case we are using the string %alias<br />

in the join clause. That's because while we are joining against the users table and<br />

asking for an alias of "u", we may end up with a different alias if that alias already<br />

exists in this query. Although we're quite sure that's not the case here, it could be<br />

the case in query_alter() hooks, so it's a good habit to get into.<br />

[ 366 ]

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!