You are here

public function RelationRepository::relationExists in Relation 8

Same name and namespace in other branches
  1. 8.2 src/Entity/RelationRepository.php \Drupal\relation\Entity\RelationRepository::relationExists()

Checks if a relation exists.

The following example demonstrates how to check if a relation of type 'likes' exists between two entities, user 17 and node 253.

$endpoints = array(
  array(
    'entity_type' => 'user',
    'entity_id' => 17,
  ),
  array(
    'entity_type' => 'node',
    'entity_id' => 253,
  ),
);
$relation_type = 'likes';
$results = Relation::relationExists($endpoints, $relation_type);

Parameters

array $endpoints: An array containing endpoints. Each endpoint is an array with keys 'entity_type' and 'entity_id'. The keys of each endpoint correspond to 'r_index' if $enforce_direction is TRUE.

string $relation_type: (Optional) The relation type (bundle) of the relation to be checked.

bool $enforce_direction: (Optional) Whether to enforce direction as specified in $endpoints.

Return value

array Array of Relation ID's keyed by revision ID.

Overrides RelationRepositoryInterface::relationExists

File

src/Entity/RelationRepository.php, line 72

Class

RelationRepository
Provides mechanism for retrieving available relations types.

Namespace

Drupal\relation\Entity

Code

public function relationExists(array $endpoints, $relation_type = NULL, $enforce_direction = FALSE) {
  $query = $this->entityQuery
    ->get('relation');
  foreach ($endpoints as $r_index => $endpoint) {
    relation_query_add_related($query, $endpoint['entity_type'], $endpoint['entity_id'], $enforce_direction ? $r_index : NULL);
  }
  if ($relation_type) {
    $query
      ->condition('relation_type', $relation_type);
  }
  $query
    ->condition('arity', count($endpoints));

  // If direction of the relation is not forced make sure the each endpoint
  // is counted just once.
  if (!$enforce_direction) {
    $query
      ->addTag('enforce_distinct_endpoints');
  }
  return $query
    ->execute();
}