D7 Create Entities and EntityFieldQuery - pierregermain/MyDrupal GitHub Wiki
Ver Typical Entity Example Nr. 4
https://www.drupal.org/project/typical_entity_example
Link: http://localhost/typical_entity_example_4
The EntityFieldQuery API permite encontrar entidades sin usar SQL.
Ejemplos sacados de https://www.drupal.org/node/1343708
Vamos a ver ejemplos, pero para entenderlo es importante entender la documentación oficial. Dicha documentación se encuentra propiamente en el codebase de drupal en el siguiente fichero: /www/includes/entity.inc
Recomiendo ver dicho fichero con phpstorm usando la pestaña Structure para ver los métodos existentes.
Obtener entidades del tipo artículo que estén publicados:
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
->entityCondition('bundle', 'article')
->propertyCondition('status', NODE_PUBLISHED)
Esto es lo que nos dice entity.inc al respecto:
/**
* Adds a condition on entity-generic metadata.
*
* If the overall query contains only entity conditions or ordering, or if
* there are property conditions, then specifying the entity type is
* mandatory. If there are field conditions or ordering but no property
* conditions or ordering, then specifying an entity type is optional. While
* the field storage engine might support field conditions on more than one
* entity type, there is no way to query across multiple entity base tables by
* default. To specify the entity type, pass in 'entity_type' for $name,
* the type as a string for $value, and no $operator (it's disregarded).
*
* 'bundle', 'revision_id' and 'entity_id' have no such restrictions.
*
* Note: The "comment" entity type does not support bundle conditions.
*
* @param $name
* 'entity_type', 'bundle', 'revision_id' or 'entity_id'.
* @param $value
* The value for $name. In most cases, this is a scalar. For more complex
* options, it is an array. The meaning of each element in the array is
* dependent on $operator.
* @param $operator
* Possible values:
* - '=', '<>', '>', '>=', '<', '<=', 'STARTS_WITH', 'CONTAINS': These
* operators expect $value to be a literal of the same type as the
* column.
* - 'IN', 'NOT IN': These operators expect $value to be an array of
* literals of the same type as the column.
* - 'BETWEEN': This operator expects $value to be an array of two literals
* of the same type as the column.
* The operator can be omitted, and will default to 'IN' if the value is an
* array, or to '=' otherwise.
*
* @return EntityFieldQuery
* The called object.
*/
public function entityCondition($name, $value, $operator = NULL) {
// The '!=' operator is deprecated in favour of the '<>' operator since the
// latter is ANSI SQL compatible.
if ($operator == '!=') {
$operator = '<>';
}
$this->entityConditions[$name] = array(
'value' => $value,
'operator' => $operator,
);
return $this;
}
/**
* Adds a condition on an entity-specific property.
*
* An $entity_type must be specified by calling
* EntityFieldCondition::entityCondition('entity_type', $entity_type) before
* executing the query. Also, by default only entities stored in SQL are
* supported; however, EntityFieldQuery::executeCallback can be set to handle
* different entity storage.
*
* @param $column
* A column defined in the hook_schema() of the base table of the entity.
* @param $value
* The value to test the field against. In most cases, this is a scalar. For
* more complex options, it is an array. The meaning of each element in the
* array is dependent on $operator.
* @param $operator
* Possible values:
* - '=', '<>', '>', '>=', '<', '<=', 'STARTS_WITH', 'CONTAINS': These
* operators expect $value to be a literal of the same type as the
* column.
* - 'IN', 'NOT IN': These operators expect $value to be an array of
* literals of the same type as the column.
* - 'BETWEEN': This operator expects $value to be an array of two literals
* of the same type as the column.
* The operator can be omitted, and will default to 'IN' if the value is an
* array, or to '=' otherwise.
*
* @return EntityFieldQuery
* The called object.
*/
public function propertyCondition($column, $value, $operator = NULL) {
// The '!=' operator is deprecated in favour of the '<>' operator since the
// latter is ANSI SQL compatible.
if ($operator == '!=') {
$operator = '<>';
}
$this->propertyConditions[] = array(
'column' => $column,
'value' => $value,
'operator' => $operator,
);
return $this;
}
Deberíás leer esta documentación cuando no sepas hacer algo. Vas a perder tiempo, si, pero vas a saber cómo usarlo bien sin usar tanto los foros y sin hacer tanto copy paste.
Esta query también está sacado del link que compartí antes.
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
->entityCondition('bundle', 'article')
->propertyCondition('status', NODE_PUBLISHED)
->fieldCondition('field_news_types', 'value', 'spotlight', '=')
// See the comment about != NULL above.
->fieldCondition('field_photo', 'fid', 'NULL', '!=')
->fieldCondition('field_faculty_tag', 'tid', $value)
->fieldCondition('field_news_publishdate', 'value', db_like($year) . '%', 'like') // Equal to "starts with"
->fieldCondition('field_news_subtitle', 'value', '%' . db_like($year) . '%', 'like') // Equal to "contains"
->fieldOrderBy('field_photo', 'fid', 'DESC')
->range(0, 10)
// Run the query as user 1.
->addMetaData('account', user_load(1));
$result = $query->execute();
if (isset($result['node'])) {
$news_items_nids = array_keys($result['node']);
$news_items = entity_load('node', $news_items_nids);
}
Es un buen ejercicio buscar para cada condición su respectivo método (tal cómo hicimos en el ejemplo básico)