Skip to content

Instantly share code, notes, and snippets.

@e0ipso
Last active December 27, 2015 16:58
Show Gist options
  • Save e0ipso/7358389 to your computer and use it in GitHub Desktop.
Save e0ipso/7358389 to your computer and use it in GitHub Desktop.
Fetch field contents without loading whole entity.
<?php
/**
* Get the content of a field for a given array of entity ids. If the field
* contains multiple values for a given entity id, then only the latest is
* preserved.
*
* @param string $field_name
* The name of the field you need to retrieve.
* @param array $entity_ids
* An array containing the entity ids to look for.
* @param string $column_name
* Name of the column in the database that holds the value for the field.
* Defaults to 'value'.
*
* @return array
* A keyed array with keys representing the entity ids and the values
* representing the value of the field.
*/
function entity_field_single_value($field_name, $entity_ids, $column_name = 'value') {
/** @var string $field_tablename Name of the SQL table that holds the field information. This will probably become 'field_data_field_whatever'. */
$field_tablename = _field_sql_storage_tablename(field_info_field($field_name));
/** @var string $field_columnname Name of the SQL column that holds the field information. This will probably become 'field_whatever_value'. */
$field_columnname = _field_sql_storage_columnname($field_name, $column_name);
return db_select($field_tablename, 'f')
->fields('f', array('entity_id', $field_columnname))
->condition('f.entity_id', $entity_ids, 'IN')
->execute()
->fetchAllKeyed();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment