18.10.2016 Views

Drupal 7 Module Development

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Appendix A<br />

The join() methods all return the alias for the table that was actually used, so we<br />

can use that in later method calls. In this case we will also select one field from the<br />

users table, the user's name, and alias it to "username". Again, since there's a slight<br />

chance the alias could already be used, addField() will return the alias that was<br />

actually used for that field.<br />

Our effective query now looks like this:<br />

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

n INNER JOIN {users} u ON u.nid = n.nid<br />

Now we need to restrict the query, that is, add the WHERE clauses. That is done with<br />

the condition() method, which takes a field name, the value to match against, and<br />

optionally a comparator. The default is equals. The above lines, therefore, add WHERE<br />

clauses for a username of 'Bob' and a node creation time within the past week (that<br />

is, where the creation timestamp is greater than or equal to the current time minus<br />

seven days' worth of seconds). For more complex conditionals there is also a where()<br />

method that takes an SQL fragment.<br />

We then tell the query to order by creation time, in descending order (DESC) and to<br />

only return five results starting with record 0, that is, the five most recently created<br />

nodes. Our SQL query now looks something like this:<br />

SELECT n.nid AS nid, n.title AS title, u.name AS username<br />

FROM {node} n<br />

INNER JOIN {users} u ON u.nid = n.nid<br />

WHERE (n.created >= 1286213869)<br />

AND (u.name = 'Bob')<br />

ORDER BY n.created DESC<br />

LIMIT 5 OFFSET 0<br />

There's one more important method to call—addTag(). This method doesn't<br />

affect the query directly but does mark the type of query it is. If a query has been<br />

tagged then before it is turned into an SQL string it will be passed through<br />

hook_query_alter() and hook_query_TAG_alter(). That allows other modules<br />

an opportunity to change the query if they need to. The node_access tag, used here,<br />

is most important as it allows the node access system to alter the query, to filter out<br />

nodes that the current user should not have access to.<br />

When querying the node table, always us a dynamic query with the<br />

node_access tag. If you do not, then you have a security hole.<br />

[ 367 ]

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

Saved successfully!

Ooh no, something went wrong!