Laravel-分页随机记录 [英] Laravel - Paginate Random records

查看:289
本文介绍了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 ?

推荐答案

当您进入

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);

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

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