Posted 11 years 11 months 1 week ago.

I had a situation similar to this:

I had to fetch a bunch of nodes using a query like select * from nodes where

In each node, load the node, using node_load, check if a field has certain value

Based on that, perform some actions on the node and save the node.

The problem here was that the nodes that I was trying to loop through belong to a content type that has like 5 fields. And doing a node_load was resource heavy as it would have to perform a join operation on 50+ tables to get the values of all the fields of the node.

My mentor Ravi J suggested that A more ideal approach for this could be to query for the entity (here node) with only the required field that I would have to check for the value and load only those nodes. This way I can avoid a node_load on all those that I would not have to perform any operations on.

Here was the EntityFieldQuery, something that I was totally unaware of till now.

An example from http://drupal.org/node/1343708

$query-?>entityCondition('entity_type', 'node')
->entityCondition('bundle', 'article')
->propertyCondition('status', 1)
->fieldCondition('field_news_types', 'value', 'spotlight', '=')
->fieldCondition('field_photo', 'fid', 'NULL', '!=')
->fieldCondition('field_faculty_tag', 'tid', $value)
->fieldCondition('field_news_publishdate', 'value', $year. '%', 'like')
->range(0, 10)
->addMetaData('account', user_load(1)); // run the query as user 1

$result = $query->execute();
if (isset($result['node'])) {
$news_items_nids = array_keys($result['node']);
$news_items = entity_load('node', $news_items_nids);
}
?>

In my case it would be

$query-?>entityCondition('entity_type', 'node')
->entityCondition('bundle', 'article')
->propertyCondition('status', 1)
->fieldCondition('some_field', 'value', 'xxx', '=')
..
..
..;
$result = $query->execute();
if (isset($result['node'])) {
$news_items_nids = array_keys($result['node']);
$news_items = entity_load('node', $news_items_nids);
//This would do an node_load of all those nodes and give me an array
//But only those which satisfy the conditions
}
?>

How to use EntityFieldQuery
http://drupal.org/node/1343708

EntityFieldQuery: Let Drupal Do The Heavy Lifting
http://treehouseagency.com/blog/tim-cosgrove/2012/02/16/entityfieldquer…
http://treehouseagency.com/blog/tim-cosgrove/2012/02/28/entityfieldquer…
http://treehouseagency.com/blog/fredric-mitchell/2012/02/21/or-queries-…

Add new comment

Submitted by tanay on Tue, 04/17/2012 - 11:21