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

我知道,通过使用SQL,您可以按RAND()进行排序。但是,我希望获得随机行,而不是在初始查询之前对记录的数量进行计数。

什么好主意吗?


当前回答

这很简单,只要检查你的laravel版本

Laravel >= 5.2:

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

或者对集合使用随机方法:

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

Laravel 4.2.7 - 5.1:

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

拉拉维尔 4.0 - 4.2.6:

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

Laravel 3:

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

其他回答

我有成千上万的记录表,所以我需要一些快速。这是我的伪随机行代码:

// count all rows with flag active = 1
$count = MyModel::where('active', '=', '1')->count(); 

// get random id
$random_id = rand(1, $count - 1);  

// get first record after random id
$data = MyModel::where('active', '=', '1')->where('id', '>', $random_id)->take(1)->first(); 

这很简单,只要检查你的laravel版本

Laravel >= 5.2:

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

或者对集合使用随机方法:

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

Laravel 4.2.7 - 5.1:

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

拉拉维尔 4.0 - 4.2.6:

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

Laravel 3:

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

还有whereRaw('RAND()')做同样的事情,然后你可以chain ->get()或->first(),甚至疯狂地添加->paginate(int)。

试试这段代码!工作原理:

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

使用Laravel函数

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