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