function Sql::addOrderBy

Same name in other branches
  1. 9 core/modules/views/src/Plugin/views/query/Sql.php \Drupal\views\Plugin\views\query\Sql::addOrderBy()
  2. 10 core/modules/views/src/Plugin/views/query/Sql.php \Drupal\views\Plugin\views\query\Sql::addOrderBy()
  3. 11.x core/modules/views/src/Plugin/views/query/Sql.php \Drupal\views\Plugin\views\query\Sql::addOrderBy()

Add an ORDER BY clause to the query.

Parameters

$table: The table this field is part of. If a formula, enter NULL. If you want to orderby random use "rand" as table and nothing else.

$field: The field or formula to sort on. If already a field, enter NULL and put in the alias.

$order: Either ASC or DESC.

$alias: The alias to add the field as. In SQL, all fields in the order by must also be in the SELECT portion. If an $alias isn't specified one will be generated for from the $field; however, if the $field is a formula, this alias will likely fail.

$params: Any params that should be passed through to the addField.

File

core/modules/views/src/Plugin/views/query/Sql.php, line 1026

Class

Sql
Views query plugin for an SQL query.

Namespace

Drupal\views\Plugin\views\query

Code

public function addOrderBy($table, $field = NULL, $order = 'ASC', $alias = '', $params = []) {
    // Only ensure the table if it's not the special random key.
    // @todo: Maybe it would make sense to just add an addOrderByRand or something similar.
    if ($table && $table != 'rand') {
        $this->ensureTable($table);
    }
    // Only fill out this aliasing if there is a table;
    // otherwise we assume it is a formula.
    if (!$alias && $table) {
        $as = $table . '_' . $field;
    }
    else {
        $as = $alias;
    }
    if ($field) {
        $as = $this->addField($table, $field, $as, $params);
    }
    $this->orderby[] = [
        'field' => $as,
        'direction' => strtoupper($order),
    ];
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.