Laravel - 对随机记录进行分页
我们如何在 Laravel 中对随机记录进行分页?例如:
How we can paginate through random records in laravel? for example:
$products = Product::all()->orderBy(DB::raw('RAND()'));
$products->paginate(4);
$products->setPath('products');
由于顺序随机,以上将以重复记录结束.如何保留 $products 对象,以便在发出新页面请求时,它应该过滤相同/固定的随机记录集?
Above will ends in duplicate records, because of random order. How can I persist the $products object so that, when a new page request made, it should filter though same/fixed random record set ?
推荐答案
当你深入到 mysql 文档并搜索 RAND() 功能,您将看到您可以使用种子".
Whe you dive into the documentation of mysql and search for the RAND() functionality you will see you can use a "seed".
通过使用种子,您将始终获得相同的随机结果.
By using a seed you will always get the same results that are randomised.
示例:
$products = Product
::all()
->orderBy(DB::raw('RAND(1234)'))
->paginate(4);
您可以生成自己的种子并将其存储在会话或其他内容中以供记住.
You can generate your own seed and store in in a session or something to remember it.
更新
Laravel 查询构建器 现在有一个功能完全一样:
The Laravel query builder now has a function that does exactly the same:
$products = Product
::all()
->inRandomOrder('1234')
->paginate(4);
相关文章