Home > PHP Framework > ThinkPHP > body text

How to use ThinkPHP5 for database query sorting

WBOY
Release: 2023-05-28 20:37:15
forward
2004 people have browsed it

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

Among them, DESC means descending order, and ASC means ascending order.

Example:

<code><div class="code" style="position:relative; padding:0px; margin:0px;"><div class="code" style="position:relative; padding:0px; margin:0px;"><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><div class="contentsignin">Copy after login</div></div><div class="contentsignin">Copy after login</div></div>

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();
Copy after login

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

<code><div class="code" style="position:relative; padding:0px; margin:0px;"><div class="code" style="position:relative; padding:0px; margin:0px;"><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><div class="contentsignin">Copy after login</div></div><div class="contentsignin">Copy after login</div></div>

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

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!

Related labels:
source:yisu.com
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