You are here

public function Select::orderBy in Drupal 9

Same name in this branch
  1. 9 core/lib/Drupal/Core/Database/Query/Select.php \Drupal\Core\Database\Query\Select::orderBy()
  2. 9 core/lib/Drupal/Core/Database/Driver/pgsql/Select.php \Drupal\Core\Database\Driver\pgsql\Select::orderBy()
Same name and namespace in other branches
  1. 8 core/lib/Drupal/Core/Database/Query/Select.php \Drupal\Core\Database\Query\Select::orderBy()

Orders the result set by a given field.

If called multiple times, the query will order by each specified field in the order this method is called.

If the query uses DISTINCT or GROUP BY conditions, fields or expressions that are used for the order must be selected to be compatible with some databases like PostgreSQL. The PostgreSQL driver can handle simple cases automatically but it is suggested to explicitly specify them. Additionally, when ordering on an alias, the alias must be added before orderBy() is called.

Parameters

$field: The field on which to order. The field is escaped for security so only valid field and alias names are possible. To order by an expression, add the expression with addExpression() first and then use the alias to order on.

Example:

$query
  ->addExpression('SUBSTRING([thread], 1, (LENGTH([thread]) - 1))', 'order_field');
$query
  ->orderBy('order_field', 'ASC');

$direction: The direction to sort. Legal values are "ASC" and "DESC". Any other value will be converted to "ASC".

Return value

$this The called object.

Overrides SelectInterface::orderBy

1 call to Select::orderBy()
Select::orderRandom in core/lib/Drupal/Core/Database/Query/Select.php
Orders the result set by a random value.
1 method overrides Select::orderBy()
Select::orderBy in core/lib/Drupal/Core/Database/Driver/pgsql/Select.php
Overrides SelectQuery::orderBy().

File

core/lib/Drupal/Core/Database/Query/Select.php, line 655

Class

Select
Query builder for SELECT statements.

Namespace

Drupal\Core\Database\Query

Code

public function orderBy($field, $direction = 'ASC') {

  // Only allow ASC and DESC, default to ASC.
  $direction = strtoupper($direction) == 'DESC' ? 'DESC' : 'ASC';
  $this->order[$field] = $direction;
  return $this;
}