Do I just do a direct db_query()
on node/node_revision, or is there a function?
2 Answers
You use db_query()
to get the node IDs for all the nodes of a content type, and then node_load() to load the single nodes one by one.
$query = db_query("SELECT nid FROM {node} WHERE type = '%s'", $type);
while ($result = db_fetch_object($query)) {
$node = node_load($result->nid);
// Use $node or store it in an array;
}
As the query is fetching a single field, db_fetch_object()
could probably be replaced with db_result(); I have never checked if it works for all the database engines, and I didn't find a Drupal core module that uses db_result()
in a loop (e.g., while ($nid = db_result($query))
).
The reason you should use node_load()
is that:
It allows the module that define the content type for the loaded node, and third-party modules to add extra fields in the node object. This is because the function uses the following code:
// Call the node specific callback (if any) and piggy-back the // results to the node or overwrite some values. if ($extra = node_invoke($node, 'load')) { foreach ($extra as $key => $value) { $node->$key = $value; } } if ($extra = node_invoke_nodeapi($node, 'load')) { foreach ($extra as $key => $value) { $node->$key = $value; } }
It loads the correct node revision, when revisions are enabled for the content type.
- It caches the result; if two calls to the functions are requiring the same node, the function simply return the previous result. This happens if the call to the function doesn't require a specific revision of the module, and if the last parameter passed to the function (
$reset
) is not equal toTRUE
.
If you are interested to get only the node ID, then the call to db_query()
is sufficient.
In Drupal 7, there is a class that allows to load multiple entities (Drupal 7 nodes are entities) that match some criteria in once: EntityFieldQuery.
You do a query with db_query()
db_query("SELECT nid FROM {node} WHERE type = 'type';");