How to query a field on an entity in Drupal 7

With Drupal 7's support for Field API, even the die-hard opponents of old-style CCK will find themselves using fields, and (hopefully) entities.  But...how do you run a query efficiently on a field which could have multiple values?

The answer lies in EntityFieldQuery.  Here are some examples of how it can be used:

$query = new EntityFieldQuery();

$query
->entityCondition('entity_type', 'taxonomy_term', '=')
->propertyCondition('vid', 2) fieldCondition('field_your_textfield',
->'value', array('value to search for'), '=');

dpm($query->execute());


$query = new EntityFieldQuery();
$entities = $query->entityCondition('entity_type', 'node')
                        ->entityCondition('bundle', 'event')
                        ->propertyCondition('status', 1)
                        ->fieldCondition('field_date', 'value', array('2011-03-01', '2011-03-31'), 'BETWEEN')
                        ->fieldOrderBy('field_date', 'value', 'ASC')
                        ->execute();

$nodes = entity_load('node', array_keys($entities['node'])); return node_view_multiple($nodes, 'teaser');

 

You can find more useful discussion on the topic at http://drupal.org/node/916776 or http://drupal.stackexchange.com/questions/3/whats-the-proper-use-of-entityfieldquery

Tags: 

Add new comment