[Drupal] What is Entity Field Query in Drupal 7
Entity Field query in Drupal 7 is the querying technique used in the Drupal to cut short the huge queries. It is like an ORM(object relation mapping) technique like doctrine. Let us go through the entity Field querying methods.
Entity Types in Drupal
There are 4 basic entity types in the drupal core. Data storage is on the basis of the entity types.
- Nodes (content)
- Comments
- Taxonomy terms
- User profiles
As the node data saved on different tables, if we use db api query it will really be a hard nut to create custom queries. There lies the entity Field Query(EFQ). It allows finding of entities based on entity properties, field values, and other entity metadata. The syntax is really concise and easy to follow.
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node') // Selecting the node type
->entityCondition('bundle', 'article') // Selecting the article bundle
->propertyCondition('status', 1) // Status =1 means; published content only
->fieldCondition('another_node_field', 'value',
'value_to_compare', '=')
->fieldOrderBy('another_field', 'id', 'DESC') // Setting the order by
->range(0, 10) // Setting the range limit, offset
$result = $query->execute();
if (isset($result['node'])) {
$news_items_nids = array_keys($result['node']);
$news_items = entity_load('node', $news_items_nids); // Loading the entity node withe result node ids
}
About Entity_load()
// Syntax is:
entity_load($entity_type, $ids) // Entity type-> node, comment, taxonomy, user
It will load all the data according to the query from the database. The return value will be an array of entity objects indexed by their ids and for no result, an empty array would return.