You are here

public function SearchApiQuery::addOrderBy in Search API 8

Adds an ORDER BY clause to the query.

This replicates the interface of Views' default SQL backend to simplify the Views integration of the Search API. If you are writing Search API-specific Views code, you should better use the sort() method directly.

Currently, only random sorting (by passing "rand" as the table) is supported (for backends that support it), all other calls are silently ignored.

Parameters

string|null $table: The table this field is part of. If you want to order the results randomly, use "rand" as table and nothing else. Otherwise, use NULL.

string|null $field: (optional) Ignored.

string $order: (optional) Either ASC or DESC. (Lowercase variants will be uppercased.)

string $alias: (optional) The field to sort on. Unless sorting randomly, "search_api_id" and "search_api_datasource" are supported.

array $params: (optional) For sorting randomly, additional random sort parameters can be passed through here. Otherwise, the parameter is ignored.

Throws

\Drupal\search_api\SearchApiException Thrown if the searched index's server couldn't be loaded.

See also

\Drupal\views\Plugin\views\query\Sql::addOrderBy()

File

src/Plugin/views/query/SearchApiQuery.php, line 1282

Class

SearchApiQuery
Defines a Views query class for searching on Search API indexes.

Namespace

Drupal\search_api\Plugin\views\query

Code

public function addOrderBy($table, $field = NULL, $order = 'ASC', $alias = '', array $params = []) {
  $server = $this
    ->getIndex()
    ->getServerInstance();
  if ($table == 'rand') {
    if ($server
      ->supportsFeature('search_api_random_sort')) {
      $this
        ->sort('search_api_random', $order);
      if ($params) {
        $this
          ->setOption('search_api_random_sort', $params);
      }
    }
    else {
      $variables['%server'] = $server
        ->label();
      $this
        ->getLogger()
        ->warning('Tried to sort results randomly on server %server which does not support random sorting.', $variables);
    }
  }
  elseif (in_array($alias, [
    'search_api_id',
    'search_api_datasource',
  ])) {
    $order = strtoupper($order) === 'DESC' ? 'DESC' : 'ASC';
    $this
      ->sort($alias, $order);
  }
}