沃梦达 / 编程问答 / php问题 / 正文

Laravel - 对随机记录进行分页

Laravel - Paginate Random records(Laravel - 对随机记录进行分页)

本文介绍了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);

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

本文标题为:Laravel - 对随机记录进行分页

基础教程推荐