Home > PHP Framework > Laravel > laravel randomly extracts n pieces of data from mysql database (high performance)

laravel randomly extracts n pieces of data from mysql database (high performance)

藏色散人
Release: 2020-07-03 11:55:23
forward
3920 people have browsed it

The following tutorial column from Laravel will introduce to you how laravel randomly extracts n pieces of data from the mysql database. I hope it will be helpful to friends in need!

laravel randomly extracts n pieces of data from mysql database (high performance)

How does laravel randomly obtain n pieces of data from the mysql database with high performance? Sometimes we often need to randomly obtain data from the database, for example: randomly assign 10 to the staff order, randomly check 100 users from the database; in this way, we need to randomly obtain data from the database.

1. Use native SQL to obtain 100 pieces of data from the database

As you can see from the Mysql official website, you can ORDER BY RAND () Used together with LIMIT, can be used to select a random part from multiple rows of results.

SELECT * FROM table WHERE name="" ORDER BY RAND() LIMIT 100;
Copy after login

Then using native SQL in laravel is also very simple, as shown below:

$info = DB::select('SELECT * FROM table WHERE name="" ORDER BY RAND() LIMIT 100');
Copy after login

2. Use original expressions to randomly obtain data from the data

We all know the original expression of laravel, we can use DB::raw('RAND()') to get random data from the database. At the same time, you can also use orderByRaw('RAND()') to randomly obtain data from the database, which has the same effect as DB::raw('RAND()')

$info=self::where(&#39;dealing&#39;,&#39;<>&#39;,&#39;&#39;)
        ->orderBy(DB::raw(&#39;RAND()&#39;))
        ->take(5)
        ->get();
Copy after login

3. Use laravel's inRandomOrder method to randomly obtain data

laravel uses inRandomOrder to randomly sort the data results to achieve the goal of randomly obtaining data from the database. Effect:

$info = DB::table(&#39;users&#39;)
            ->inRandomOrder()
            ->take(5)
            ->get();
Copy after login

The above is the detailed content of laravel randomly extracts n pieces of data from mysql database (high performance). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
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