Home >PHP Framework >ThinkPHP >How to use ThinkPHP5 for database query sorting
Sorting is a common requirement when performing database queries. Data sorting can make it easier for us to understand the meaning of the data and perform analysis. For ThinkPHP5, query results can be sorted by calling the order() method.
First, we need to understand the basic syntax of the order() method. The order() method uses the following form:
->order('字段1 DESC,字段2 ASC')
Among them, DESC means descending order, and ASC means ascending order.
Example:
<code><pre class="brush:php;toolbar:false">$data = Db::table(&#39;user&#39;)->where(&#39;age&#39;, &#39;>&#39;, 18)->order(&#39;age DESC,name ASC&#39;)->select();</pre>
In the above example, we select age greater than 18 years old from the user data table users, sorted by age in descending order and by name in ascending order.
We can also simply pass the field name that needs to be sorted:
$data = Db::table('user')->where('age', '>', 18)->order('age DESC')->select();
If you want to pass between multiple fields, use commas to separate them:
<code><pre class="brush:php;toolbar:false">$data = Db::table(&#39;user&#39;)->where(&#39;age&#39;, &#39;>&#39;, 18)->order(&#39;age DESC,name ASC&#39;)->select();</pre>
We can also paginate the results like this:
$data = Db::table('user')->where('age', '>', 18)->order('age DESC')->paginate(10);
In the above example, we divide the results into 10 records per page to facilitate more accurate Handles large data sets well.
The above is the detailed content of How to use ThinkPHP5 for database query sorting. For more information, please follow other related articles on the PHP Chinese website!