Home >Backend Development >PHP Tutorial >How to Sort a Laravel Query Builder Result by Multiple Columns?

How to Sort a Laravel Query Builder Result by Multiple Columns?

DDD
DDDOriginal
2024-11-09 16:11:02263browse

How to Sort a Laravel Query Builder Result by Multiple Columns?

Sorting a Laravel Query Builder Result by Multiple Columns

When working with Laravel Eloquent, you may need to sort a query builder result by multiple columns. To achieve this, utilize the orderBy() method. This method allows you to specify multiple columns and their respective sort orders.

Example:

Consider the following scenario where you want to sort the mytable table by two columns: column1 in descending order and column2 in ascending order.

SQL Statement:

SELECT *
FROM mytable
ORDER BY
  column1 DESC, column2 ASC

Laravel Query Builder Code:

User::orderBy('name', 'DESC')
    ->orderBy('email', 'ASC')
    ->get();

This code will generate the following SQL query:

SELECT * FROM `users` ORDER BY `name` DESC, `email` ASC

The above is the detailed content of How to Sort a Laravel Query Builder Result by Multiple Columns?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn