php Laravel - Eloquent 或 Fluent 随机行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13917558/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 06:15:43  来源:igfitidea点击:

Laravel - Eloquent or Fluent random row

phpfluentlaraveleloquent

提问by DigitalWM

How can I select a random row using Eloquent or Fluent in Laravel framework?

如何在 Laravel 框架中使用 Eloquent 或 Fluent 选择随机行?

I know that by using SQL, you can do order by RAND(). However, I would like to get the random row withoutdoing a count on the number of records prior to the initial query.

我知道通过使用 SQL,您可以通过 RAND() 进行排序。但是,我想在初始查询之前计算记录数的情况下获取随机行。

Any ideas?

有任何想法吗?

回答by aebersold

Laravel >= 5.2:

Laravel >= 5.2:

User::all()->random();
User::all()->random(10); // The amount of items you wish to receive

or

或者

User::inRandomOrder()->get();

or to get the Specific number of records

或获取特定记录数

//5 indicates the number of records
User::inRandomOrder()->limit(5)->get();

Laravel 4.2.7 - 5.1:

Laravel 4.2.7 - 5.1:

User::orderByRaw("RAND()")->get();

Laravel 4.0 - 4.2.6:

Laravel 4.0 - 4.2.6:

User::orderBy(DB::raw('RAND()'))->get();

Laravel 3:

Laravel 3:

User::order_by(DB::raw('RAND()'))->get();

Check this articleon MySQL random rows. Laravel 5.2 supports this, for older version, there is no better solution then using RAW Queries.

查看这篇关于 MySQL 随机行的文章。Laravel 5.2 支持这一点,对于旧版本,没有比使用RAW Queries更好的解决方案。

edit 1:As mentioned by Double Gras, orderBy() doesn't allow anything else then ASC or DESC since thischange. I updated my answer accordingly.

编辑 1:正如 Double Gras 所提到的, orderBy() 不允许除 ASC 或 DESC 之外的任何其他内容,因为更改。我相应地更新了我的答案。

edit 2:Laravel 5.2 finally implements a wrapper functionfor this. It's called inRandomOrder().

编辑 2:Laravel 5.2 终于为此实现了一个包装函数。它被称为inRandomOrder()

回答by manish

This works just fine,

这工作得很好,

$model=Model::all()->random(1)->first();

you can also change argument in random function to get more than one record.

您还可以更改随机函数中的参数以获得多个记录。

Note: not recommended if you have huge data as this will fetch all rows first and then returns random value.

注意:如果您有大量数据,则不建议这样做,因为这将首先获取所有行,然后返回随机值。

回答by Gras Double

tl;dr:It's nowadays implemented into Laravel, see "edit 3" below.

tl; dr:它现在已在 Laravel 中实现,请参阅下面的“编辑 3”。



Sadly, as of today there are some caveats with the ->orderBy(DB::raw('RAND()'))proposed solution:

可悲的是,截至今天,->orderBy(DB::raw('RAND()'))提议的解决方案有一些警告:

  • It isn't DB-agnostic. e.g. SQLite and PostgreSQL use RANDOM()
  • Even worse, this solution isn't applicable anymore since this change:

    $direction = strtolower($direction) == 'asc' ? 'asc' : 'desc';

  • 它不是数据库不可知的。例如 SQLite 和 PostgreSQL 使用RANDOM()
  • 更糟糕的是,此解决方案不再适用,因为此更改

    $direction = strtolower($direction) == 'asc' ? 'asc' : 'desc';


edit:Now you can use the orderByRaw()method: ->orderByRaw('RAND()'). However this is still not DB-agnostic.


编辑:现在你可以使用orderByRaw()方法:->orderByRaw('RAND()')。然而,这仍然不是数据库不可知的。

FWIW, CodeIgniter implements a special RANDOMsorting direction, which is replaced with the correct grammar when building query. Also it seems to be fairly easy to implement. Looks like we have a candidate for improving Laravel :)

FWIW,CodeIgniter 实现了一个特殊的RANDOM排序方向,在构建查询时替换为正确的语法。它似乎也很容易实现。看起来我们有一个改进 Laravel 的候选人:)

update: here is the issueabout this on GitHub, and my pending pull request.

更新:这是GitHub 上有关此问题的问题,以及我的待处理拉取请求


edit 2:Let's cut the chase. Since Laravel 5.1.18 you can add macros to the query builder:


编辑2:让我们停止追逐。从 Laravel 5.1.18 开始,您可以向查询构建器添加宏:

use Illuminate\Database\Query\Builder;

Builder::macro('orderByRandom', function () {

    $randomFunctions = [
        'mysql'  => 'RAND()',
        'pgsql'  => 'RANDOM()',
        'sqlite' => 'RANDOM()',
        'sqlsrv' => 'NEWID()',
    ];

    $driver = $this->getConnection()->getDriverName();

    return $this->orderByRaw($randomFunctions[$driver]);
});

Usage:

用法:

User::where('active', 1)->orderByRandom()->limit(10)->get();

DB::table('users')->where('active', 1)->orderByRandom()->limit(10)->get();


edit 3:Finally! Since Laravel 5.2.33 (changelog, PR #13642) you can use the native method inRandomOrder():


编辑3:终于!从 Laravel 5.2.33 ( changelog, PR #13642) 开始,你可以使用原生方法inRandomOrder()

User::where('active', 1)->inRandomOrder()->limit(10)->get();

DB::table('users')->where('active', 1)->inRandomOrder()->limit(10)->get();

回答by Teodor Talov

In Laravel 4 and 5the order_byis replaced by orderBy

Laravel 4 和 5order_by被替换为orderBy

So, it should be:

所以,应该是:

User::orderBy(DB::raw('RAND()'))->get();

回答by simhumileco

You can use:

您可以使用

ModelName::inRandomOrder()->first();

回答by Manuel Azar

For Laravel 5.2 >=

对于 Laravel 5.2 >=

use the Eloquent method:

使用 Eloquent 方法:

inRandomOrder()

The inRandomOrder method may be used to sort the query results randomly. For example, you may use this method to fetch a random user:

inRandomOrder 方法可用于对查询结果进行随机排序。例如,您可以使用此方法来获取随机用户:

$randomUser = DB::table('users')
            ->inRandomOrder()
            ->first();

from docs: https://laravel.com/docs/5.2/queries#ordering-grouping-limit-and-offset

来自文档:https: //laravel.com/docs/5.2/queries#ordering-grouping-limit-and-offset

回答by Bilal Gultekin

You can also use order_by method with fluent and eloquent like as:

您还可以使用 order_by 方法流畅而雄辩,例如:

Posts::where_status(1)->order_by(DB::raw(''),DB::raw('RAND()')); 

This is a little bit weird usage, but works.

这是一个有点奇怪的用法,但有效。

Edit: As @Alex said, this usage is cleaner and also works:

编辑:正如@Alex 所说,这种用法更干净,也有效:

Posts::where_status(1)->order_by(DB::raw('RAND()'));

回答by hosein azimi

You can easily Use this command:

您可以轻松使用此命令:

// Question : name of Model
// take 10 rows from DB In shuffle records...

// 问题:模型名称
// 从 DB 中取 10 行 In shuffle 记录...

$questions = Question::orderByRaw('RAND()')->take(10)->get();

回答by Kamlesh Paul

Use Laravel function

使用 Laravel 函数

ModelName::inRandomOrder()->first();

回答by AlmostPitt

Laravel has a built-in method to shuffle the order of the results.

Laravel 有一个内置的方法来打乱结果的顺序。

Here is a quote from the documentation:

这是文档中的引用:

shuffle()

The shuffle method randomly shuffles the items in the collection:

shuffle 方法随机打乱集合中的项目:

$collection = collect([1, 2, 3, 4, 5]);

$shuffled = $collection->shuffle();

$shuffled->all();

// [3, 2, 5, 1, 4] - (generated randomly)

You can see the documentation here.

您可以在此处查看文档