The orderBy() method specifies the ORDER BY fragment of a SQL query.For example consider our employee table having fields emp_id, emp_first_name, emp_last_name and emp_salary.Suppose we need to order the result by increasing order of employee salaries.We can do it in sql as given below.
Select * from employee order by emp_salary
In yii2, we can build the query as given below
//creates a new \yii\db\Query() object
$query=new \yii\db\Query();
$rows= $query->from('employee')->orderBy([
'emp_salary' => SORT_ASC //specify sort order ASC for ascending DESC for descending
])->all();
If we need to order the employees with their first name in ascending order and then their salaries in descending order, we can write it in plain sql as follows.
Select * from employee order by emp_first_name ASC, emp_salary DESC
The equivalent sql can be build using yii2 as follows
//creates a new \yii\db\Query() object
$query=new \yii\db\Query();
$rows= $query->from('employee')->orderBy([
'emp_first_name' => SORT_ASC
'emp_salary' => SORT_DESC
])->all();
You can also specify ORDER BY using a string, just like you do when writing raw SQL statements. For example ,the above query can also be generated as given below.
//creates a new \yii\db\Query() object
$query=new \yii\db\Query();
$rows=$query->from('employee')->orderBy('emp_first_name ASC, emp_salary DESC')->all();
You can call addOrderBy() to add additional columns to the ORDER BY fragment. For example
//creates a new \yii\db\Query() object
$query=new \yii\db\Query();
$rows=$query->from('employee')->orderBy('emp_first_name ASC')
->addOrderBy('emp_salary DESC')->all();