Home  >  Article  >  PHP Framework  >  How to use ThinkPHP5 for database query sorting

How to use ThinkPHP5 for database query sorting

WBOY
WBOYforward
2023-05-28 20:37:151972browse

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(&amp;#39;user&amp;#39;)-&gt;where(&amp;#39;age&amp;#39;, &amp;#39;&gt;&amp;#39;, 18)-&gt;order(&amp;#39;age DESC,name ASC&amp;#39;)-&gt;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(&#39;user&#39;)->where(&#39;age&#39;, &#39;>&#39;, 18)->order(&#39;age DESC&#39;)->select();

If you want to pass between multiple fields, use commas to separate them:

<code><pre class="brush:php;toolbar:false">$data = Db::table(&amp;#39;user&amp;#39;)-&gt;where(&amp;#39;age&amp;#39;, &amp;#39;&gt;&amp;#39;, 18)-&gt;order(&amp;#39;age DESC,name ASC&amp;#39;)-&gt;select();</pre>

We can also paginate the results like this:

$data = Db::table(&#39;user&#39;)->where(&#39;age&#39;, &#39;>&#39;, 18)->order(&#39;age DESC&#39;)->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!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete