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

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

藏色散人
藏色散人forward
2020-07-03 11:54:503880browse

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;

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');

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();

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();

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!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete
Previous article:What is a Blade template?Next article:What is a Blade template?