function relation_get_related_entity in Relation 7
Same name and namespace in other branches
- 8.2 relation.module \relation_get_related_entity()
- 8 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
$entity_type: The entity type of one of the endpoints.
$entity_id: The entity id of one of the endpoints.
$relation_type: (optional) The relation type of the relation to find.
$r_index: (optional) The index of the search entity in the relation to be found (0 = source, 1 = target).
Return value
The entity object from the other endpoint.
1 call to relation_get_related_entity()
- RelationAPITestCase::testRelationTypes in tests/
relation.test - 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 869 - Describes relations between entities.
Code
function relation_get_related_entity($entity_type, $entity_id, $relation_type = NULL, $r_index = 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}:{$r_index}";
if (isset($items[$cache_key])) {
$entities = $items[$cache_key];
}
elseif ($cached = cache_get('relation:' . $cache_key)) {
$entities = $cached->data;
$items[$cache_key] = $entities;
}
else {
$query = relation_query($entity_type, $entity_id, $r_index)
->range(0, 1);
if ($relation_type) {
$query
->entityCondition('bundle', $relation_type);
}
$results = $query
->execute();
$result = reset($results);
if ($result) {
$relation = relation_load($result->rid);
if ($relation->arity == 1) {
$entities = FALSE;
}
else {
$entities = field_get_items('relation', $relation, 'endpoints');
}
}
else {
$entities = FALSE;
}
cache_set('relation:' . $cache_key, $entities);
$items[$cache_key] = $entities;
}
if ($entities) {
$first_entity_key = $entities[0]['entity_type'] . ':' . $entities[0]['entity_id'];
if (isset($r_index)) {
$request_key = $request_key . ':' . $r_index;
$first_entity_key = $first_entity_key . ':' . $entities[0]['r_index'];
}
if ($request_key == $first_entity_key) {
$other_endpoints = entity_load($entities[1]['entity_type'], array(
$entities[1]['entity_id'],
));
return reset($other_endpoints);
}
$other_endpoints = entity_load($entities[0]['entity_type'], array(
$entities[0]['entity_id'],
));
return reset($other_endpoints);
}
return FALSE;
}