Home > PHP Framework > Laravel > body text

How to use distinct method in laravel

WBOY
Release: 2022-06-06 11:03:42
Original
3049 people have browsed it

In laravel, the distinct() method is used to force the search to return unique results. The syntax is "$users=DB::table('users')->distinct()->get ();"; If you want to find multiple fields, you can specify the select field and add the field name.

How to use distinct method in laravel

#The operating environment of this article: Windows 10 system, Laravel version 6, Dell G3 computer.

How to use the distinct method in laravel

DB::table('table_name')->distinct()->get(['column_name']);
Copy after login

How to use distinct() and deduplication in laravel, MySQL usually uses GROUPBY (essentially a sorting action) to complete the DISTINCT operation. If the DISTINCT operation and When ORDERBY operations are used in combination, temporary tables are usually used. This will affect performance. In some cases, MySQL can use indexes to optimize DISTINCT operations, but it needs to be learned and used.

How to use distinct

laravel5 Using distinct is very simple. The official method has provided a distinct method that allows you to force the search to return unique results:

$users = DB::table('users')->distinct()->get();
Copy after login

However, the officially provided code cannot search and return unique results. We need to specify the fields:

$users=DB::table('users')->select('name')->distinct()->get();
Copy after login

How to select multiple fields

If you want to distinct fields, you can add field names in select; but be aware that when selecting multiple fields, it means that the status and name need to be the same to be excluded

$users=DB::table('users')->select('status','name')->distinct()->get();
Copy after login

This is distinct in laravel A summary of the usage methods. If you want to obtain data from the database without duplication, you can use the GROUPBY method.

[Related recommendations: laravel video tutorial]

The above is the detailed content of How to use distinct method in laravel. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!