Skip to content

Instantly share code, notes, and snippets.

@quicksketch
Last active April 26, 2018 21:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save quicksketch/7f607798b0078f5486b06cb6c510efb0 to your computer and use it in GitHub Desktop.
Save quicksketch/7f607798b0078f5486b06cb6c510efb0 to your computer and use it in GitHub Desktop.
How Entity Reference module builds its SQL query
<?php
/**
* Build an EntityFieldQuery to get referencable entities.
*/
protected function buildEntityFieldQuery($match = NULL, $match_operator = 'CONTAINS') {
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', $this->field['settings']['target_type']);
if (!empty($this->field['settings']['handler_settings']['target_bundles'])) {
$query->entityCondition('bundle', $this->field['settings']['handler_settings']['target_bundles'], 'IN');
}
if (isset($match)) {
$entity_info = entity_get_info($this->field['settings']['target_type']);
if (isset($entity_info['entity keys']['label'])) {
$query->propertyCondition($entity_info['entity keys']['label'], $match, $match_operator);
}
}
// Add a generic entity access tag to the query.
$query->addTag($this->field['settings']['target_type'] . '_access');
$query->addTag('entityreference');
$query->addMetaData('field', $this->field);
$query->addMetaData('entityreference_selection_handler', $this);
// Add the sort option.
if (!empty($this->field['settings']['handler_settings']['sort'])) {
$sort_settings = $this->field['settings']['handler_settings']['sort'];
if ($sort_settings['type'] == 'property') {
$query->propertyOrderBy($sort_settings['property'], $sort_settings['direction']);
}
elseif ($sort_settings['type'] == 'field') {
list($field, $column) = explode(':', $sort_settings['field'], 2);
$query->fieldOrderBy($field, $column, $sort_settings['direction']);
}
}
return $query;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment