如何在Laravel框架中使用Eloquent或Fluent选择随机行?
我知道,通过使用SQL,您可以按RAND()进行排序。但是,我希望获得随机行,而不是在初始查询之前对记录的数量进行计数。
什么好主意吗?
如何在Laravel框架中使用Eloquent或Fluent选择随机行?
我知道,通过使用SQL,您可以按RAND()进行排序。但是,我希望获得随机行,而不是在初始查询之前对记录的数量进行计数。
什么好主意吗?
当前回答
Laravel有一个内置的方法来打乱结果的顺序。
以下是文档中的一段话:
shuffle()
shuffle方法随机洗牌集合中的项:
$collection = collect([1, 2, 3, 4, 5]);
$shuffled = $collection->shuffle();
$shuffled->all();
// [3, 2, 5, 1, 4] - (generated randomly)
您可以在这里看到文档。
其他回答
试试这段代码!工作原理:
User::orderBy(DB::raw('RAND()'))->get();
你也可以使用order_by方法,如:
Posts::where_status(1)->order_by(DB::raw(''),DB::raw('RAND()'));
这是一个有点奇怪的用法,但是有用。
编辑:正如@Alex所说,这种用法更简洁,也有效:
Posts::where_status(1)->order_by(DB::raw('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();
以下是我如何在我的一个项目中获得雄辩的随机结果:
$products = Product::inRandomOrder()->limit(10);
10 -随机记录的数量。
使用Laravel函数
ModelName::inRandomOrder()->first();