function relation_get_related_entity in Relation 8.2
Same name and namespace in other branches
- 8 relation.module \relation_get_related_entity()
- 7 relation.module \relation_get_related_entity()
Returns a related entity.
Returns the entity object of the first other entity in the first relation that matches the given conditions. Do not expect to get exactly what you want, especially if you have multiple relations of the same type on the search entity.
Parameters
string $entity_type: The entity type of one of the endpoints.
int $entity_id: The entity id of one of the endpoints.
string|null $relation_type: (optional) The relation type of the relation to find.
int|null $delta: (optional) The index of the search entity in the relation to be found (0 = source, 1 = target).
Return value
\Drupal\Core\Entity\EntityInterface|bool The entity object from the other endpoint or FALSE.
1 call to relation_get_related_entity()
- RelationAPITest::testRelationTypes in src/
Tests/ RelationAPITest.php - Tests relation types.
1 string reference to 'relation_get_related_entity'
- relation_clear_related_entities_cache in ./
relation.module - Clear the cache for a set of endpoints.
File
- ./
relation.module, line 201 - Describes relations between entities.
Code
function relation_get_related_entity($entity_type, $entity_id, $relation_type = NULL, $delta = NULL) {
// Static cache the results of relation_query() and relation_load() to avoid
// duplicate queries if this is called multiple times with the same arguments
// during a request.
$items =& drupal_static(__FUNCTION__);
$request_key = "{$entity_type}:{$entity_id}";
$cache_key = "{$request_key}:{$relation_type}:{$delta}";
if (isset($items[$cache_key])) {
$entities = $items[$cache_key];
}
elseif ($cached = \Drupal::cache()
->get("relation:{$cache_key}")) {
$entities = $cached->data;
$items[$cache_key] = $entities;
}
else {
$query = Drupal::entityQuery('relation');
relation_query_add_related($query, $entity_type, $entity_id, $delta)
->range(0, 1);
if ($relation_type) {
$query
->condition('relation_type', $relation_type);
}
$results = $query
->execute();
$relation_id = reset($results);
if ($relation_id) {
$relation = Relation::load($relation_id);
if ($relation->arity->value == 1) {
$entities = FALSE;
}
else {
$entities = $relation->endpoints;
}
}
else {
$entities = FALSE;
}
\Drupal::cache()
->set("relation:{$cache_key}", $entities);
$items[$cache_key] = $entities;
}
if ($entities) {
$first_entity_key = $entities[0]->target_type . ':' . $entities[0]->target_id;
if (isset($delta)) {
$request_key = $request_key . ':' . $delta;
$first_entity_key .= ':0';
}
if ($request_key == $first_entity_key) {
return \Drupal::entityTypeManager()
->getStorage($entities[1]->target_type)
->load($entities[1]->target_id);
}
return \Drupal::entityTypeManager()
->getStorage($entities[0]->target_type)
->load($entities[0]->target_id);
}
return FALSE;
}