Dominique De Cooman
Published on Dominique De Cooman (https://dominiquedecooman.com)

Home > Drupal 7 tip: Query your entities for field values

Dominique De Cooman
Thursday, June 23, 2011 - 17:24
Database [1]
fields [2]
entities [3]
d7tip [4]

When you query your entities on values on a field, for example you want to get all nodes via a node reference field. In our case we have an event and we want to know all referenced sessions to it.

For this we have the EntityFieldQuery class in core which makes it very easy to query fields. So no more looking in the database structure to get your value from a table, use the EntityFieldQuery class.

This way you dont have to worry how tables are created and manipulated by the field api. No more worries about broken queries on fields.

You can use it like this:

<?php
$query 
= new EntityFieldQuery();

$query
->entityCondition('entity_type', 'node', '=')
->
propertyCondition('type', 'session', '=')
->
fieldCondition('field_session_event_reference', 'nid', $event_nid, '=');

$session_ents = $query->execute();

if (
$session_ents) {
  
$session_nodes = node_load_multiple(array_keys($session_ents['node']));
  
//do stuff with the session nodes...
}
?>

For more: http://api.drupal.org/api/drupal/includes--entity.inc/class/EntityFieldQ... [5]


Source URL: https://dominiquedecooman.com/blog/drupal-7-tip-query-your-entities-field-values

Links
[1] https://dominiquedecooman.com/blog-topics/database
[2] https://dominiquedecooman.com/blog-topics/fields-0
[3] https://dominiquedecooman.com/blog-topics/entities
[4] https://dominiquedecooman.com/blog-topics/d7tip
[5] http://api.drupal.org/api/drupal/includes--entity.inc/class/EntityFieldQuery/7