Drupal how to load content fields using cck content api avoiding node load
How to load only the content fields of a node to avoid a full node load?
Sometimes in scripts you need information stored in cck fields but you dont want to do full node loads neither do you want to query the table directly because setting a field from single to multiple value would make the table location of that field change.
For example a field in the content_type_team named field_team_name_value its table would change to content_field_team_name
<?php
//So this is wrong
$content = db_fecth_object(db_query("SELECT * FROM content_type_team" WHERE nid = %d, 1));
$team_name = $content->field_team_name;
//wont output nothing when field was set to multiple
?>
The content (ckk) api has a function to get all fields in just one call: content_storage($op, $node)
<?php
//This is correct
$node = stdClass();
$node->nid = 1;
$node->vid = db_result(db_query("SELECT vid FROM {node} WHERE nid = %d",1));
$node->type = 'team';
$content = content_storage('load', $node);
$team_name = $content['field_team_name'][0]['value'];
?>
Comments
Drupal how to load content fields using cck content api avoiding node load
Good tip.
In case you only want to retrieve one field, you could still go with your first option. You can get the table and field name dynamically as follows:
$field = content_database_info(content_fields('field_team_name'));
table is in $field['table']
optionally column in $field['columns']
Drupal how to load content fields using cck content api avoiding node load
Yo, I was trying this out on a site that had some real expensive node_load calls.
content_storage('load', $node); is about 2x faster than node_load in my profiling/setup but what is much, much faster is to hijack/appropriate content_load() and pass it your faux $node object - it worked about to about 10x faster than node_load(). Note that I implemented my own static caching of what was coming back from these functions so I wouldn't lose that advantage from node_load. I'm pretty sure that for a lot of calls to content_storage() for the same node, if you don't statically cache what comes back you could easily make things worse for yourself.
using content_storage bypasses cck's dedicated cache tables, if you're using an alternate cache implementation you can avoid hitting the database at all with content_load in many cases. Even if you don't it should still work out faster with static caching.
As an added bonus, the return of content_load is an object rather than array of fields so you don't have to refactor your other code to make it compatible, it's a "drop in" replacement for node_load if all you want is cck data.
Add new comment