Laravel - Eloquent 或 Fluent 随机行 [英] Laravel - Eloquent or Fluent random row

查看:31
本文介绍了Laravel - Eloquent 或 Fluent 随机行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我知道通过使用 SQL,您可以通过 RAND() 进行排序.但是,我想获得随机行在初始查询之前对记录数进行计数.

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

有什么想法吗?

推荐答案

Laravel >= 5.2:

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

或者获取具体的记录数

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

或使用 random 方法进行集合:

or using the random method for collections:

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

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:

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

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

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

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

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

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

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

这篇关于Laravel - Eloquent 或 Fluent 随机行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆