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
Release: 2024-11-09 16:11:02
Original
221 people have browsed it

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
Copy after login

Laravel Query Builder Code:

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

This code will generate the following SQL query:

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

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template