Drupal - how to extract values of field collection using Entityfieldquery?

An EntityFieldQuery can only refer to one type of entity, it cannot represent any relationships between entities. If the entity_type in your query is a field_collection_item, then that's the type of entity that the query will return. The EntityFieldQuery has no concept of the fact that your field collections are related to nodes, or anything else for that matter.

To get the entities related to the field collections you'll have to run another EntityFieldQuery. I haven't used field collection before but I would guess the logic would look something like this:

$query = new EntityFieldQuery;
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'customer')
  ->fieldCondition('field_name_of_collection_field', 'name_of_field_collection_column', array_keys($result['field_collection_item']));

There are things that need to be changed in that code (the name of your field collection field, the column name for the field collection relationship) but it should get you started.

Actual example of the two-query approach:

function get_species_country($id_country) {
    $inner = new EntityFieldQuery();
    $inner_r = $inner->entityCondition('entity_type', 'field_collection_item')
                     ->fieldCondition('field_species_country', 'target_id', $id_country, '=')
                     ->execute();
    if(!empty($inner_r['field_collection_item'])) {
        $keys = array_keys($inner_r['field_collection_item']);
        $query = new EntityFieldQuery();
        $species_r = $query->entityCondition('entity_type', 'node')
                      ->entityCondition('bundle', self::$bundle)
                      ->fieldCondition('field_species_countries', 'value', $keys)
                      ->execute();
        if(!empty($species_r['node'])) {
            $ret = node_load_multiple(array_keys($species_r['node']));
        }
    }
    return $ret;
}

In the example above:

  • field_species_countries - Name of the field collection
  • field_species_country - Actual field inside the field collection

Limitations: I think this has some limitations because the second query contains ... WHERE field IN (1, 2, 3 ...). For MySQL this is limited by max_allowed_packet

Tags:

Entities

Nodes