You are here

protected function Query::addSort in Drupal 10

Same name and namespace in other branches
  1. 8 core/lib/Drupal/Core/Entity/Query/Sql/Query.php \Drupal\Core\Entity\Query\Sql\Query::addSort()
  2. 9 core/lib/Drupal/Core/Entity/Query/Sql/Query.php \Drupal\Core\Entity\Query\Sql\Query::addSort()

Adds the sort to the build query.

Return value

$this Returns the called object.

File

core/lib/Drupal/Core/Entity/Query/Sql/Query.php, line 185

Class

Query
The SQL storage entity query class.

Namespace

Drupal\Core\Entity\Query\Sql

Code

protected function addSort() {
  if ($this->count) {
    $this->sort = [];
  }

  // Gather the SQL field aliases first to make sure every field table
  // necessary is added. This might change whether the query is simple or
  // not. See below for more on simple queries.
  $sort = [];
  if ($this->sort) {
    foreach ($this->sort as $key => $data) {
      $sort[$key] = $this
        ->getSqlField($data['field'], $data['langcode']);
    }
  }
  $simple_query = $this
    ->isSimpleQuery();

  // If the query is set up for paging either via pager or by range or a
  // count is requested, then the correct amount of rows returned is
  // important. If the entity has a data table or multiple value fields are
  // involved then each revision might appear in several rows and this needs
  // a significantly more complex query.
  if (!$simple_query) {

    // First, GROUP BY revision id (if it has been added) and entity id.
    // Now each group contains a single revision of an entity.
    foreach ($this->sqlFields as $field) {
      $group_by = "{$field[0]}.{$field[1]}";
      $this->sqlGroupBy[$group_by] = $group_by;
    }
  }

  // Now we know whether this is a simple query or not, actually do the
  // sorting.
  foreach ($sort as $key => $sql_alias) {
    $direction = $this->sort[$key]['direction'];
    if ($simple_query || isset($this->sqlGroupBy[$sql_alias])) {

      // Simple queries, and the grouped columns of complicated queries
      // can be ordered normally, without the aggregation function.
      $this->sqlQuery
        ->orderBy($sql_alias, $direction);
      if (!isset($this->sqlFields[$sql_alias])) {
        $this->sqlFields[$sql_alias] = explode('.', $sql_alias);
      }
    }
    else {

      // Order based on the smallest element of each group if the
      // direction is ascending, or on the largest element of each group
      // if the direction is descending.
      $function = $direction == 'ASC' ? 'min' : 'max';
      $expression = "{$function}({$sql_alias})";
      $expression_alias = $this->sqlQuery
        ->addExpression($expression);
      $this->sqlQuery
        ->orderBy($expression_alias, $direction);
    }
  }
  return $this;
}