You are here

function relation_query_enforce_distinct_endpoints_alter in Relation 8

Same name and namespace in other branches
  1. 8.2 relation.module \relation_query_enforce_distinct_endpoints_alter()
  2. 7 relation.module \relation_query_enforce_distinct_endpoints_alter()

Implements hook_query_TAG_alter().

Adds conditions to query to ensure different r_index for each endpoint.

File

./relation.module, line 83
Describes relations between entities.

Code

function relation_query_enforce_distinct_endpoints_alter(AlterableInterface $query) {
  $arity = 0;

  // Get arity of the query.
  $conditions = $query
    ->conditions();
  foreach (Element::children($conditions) as $c) {
    $condition = $conditions[$c];
    if ($condition['field'] == 'relation.arity') {
      $arity = $condition['value'];
      break;
    }
  }

  // Add r_index conditions between all endpoints.
  for ($i = 0; $i < $arity; $i++) {
    for ($k = $i + 1; $k < $arity; $k++) {
      $left_suffix = !$i ? '' : '_' . ($i + 1);
      $right_suffix = !$k ? '' : '_' . ($k + 1);
      $column_left = 'relation__endpoints' . $left_suffix . '.endpoints_r_index';
      $column_right = 'relation__endpoints' . $right_suffix . '.endpoints_r_index';
      $query
        ->where("{$column_left} != {$column_right}");
    }
  }
}