简体   繁体   English

如何使用 laravel 对数据进行混洗和分页

[英]How to shuffle and paginate data with laravel

I want to shuffle and paginate data in laravel.我想对 laravel 中的数据进行洗牌和分页。

when I use this code:当我使用此代码时:

`$questions = Question::where("exam_id",$exam->id)->shuffle()->paginate(1);`

gives me this error: BadMethodCallException Call to undefined method Illuminate\Database\Eloquent\Builder::shuffle() and when I use this code:给我这个错误: BadMethodCallException 调用未定义的方法 Illuminate\Database\Eloquent\Builder::shuffle()当我使用这段代码时:

$questions = Question::where("exam_id",$exam->id)->paginate(1)->shuffle();

in dd($questions = Question::where("exam_id",$exam->id)->paginate(1)->shuffle());dd($questions = Question::where("exam_id",$exam->id)->paginate(1)->shuffle()); gives me a collection that has the first item and other items don't exist.给我一个包含第一个项目和其他项目不存在的集合。 And there is also no paging information.And when I don't use dd() gives me this error: Method Illuminate\Database\Eloquent\Collection::links does not exist.而且也没有分页信息。当我不使用dd()时,会出现此错误: Method Illuminate\Database\Eloquent\Collection::links 不存在。 While I use $questions->links() in the view .当我在视图中使用$questions->links()时。 When I use this code:当我使用此代码时:

$questions = Question::where("exam_id",$exam->id)->get()->shuffle()->paginate(1);

Gives me this error: Method Illuminate\Database\Eloquent\Collection::paginate does not exist.给我这个错误:方法 Illuminate\Database\Eloquent\Collection::paginate 不存在。

And when I use this code:当我使用这段代码时:

$questions = Question::where("exam_id",$exam->id)->inRandomOrder()->paginate(1);

It works, but the data is repeated on later pages.它可以工作,但数据会在后面的页面上重复。 For example, the data on the first page may be repeated on page seven or other pages.例如,第一页上的数据可能在第七页或其他页上重复。

In fact, I want the data to be sorted by random And then paginated so that when a data is loaded on one page not repeated on subsequent pages.实际上,我希望将数据按随机排序,然后分页,以便在一个页面上加载数据时不会在后续页面上重复。

please help me!!Thanks请帮助我!谢谢

I was facing this same problem and solved it by adding the shuffle()->all() methods to the collection variable in the view file, which seems to work perfectly.我遇到了同样的问题,并通过将 shuffle()->all() 方法添加到视图文件中的集合变量来解决它,这似乎工作得很好。

Once you pass the variable to the view to loop over using a foreach I added the following:将变量传递给视图以使用 foreach 循环后,我添加了以下内容:

$rows->shuffle()->all()

So my foreach loop looks like:所以我的 foreach 循环看起来像:

foreach($rows->shuffle()->all() as $row){... }

The rows on the front end when loaded using ajax still work as they should with the paginator since the collection is untouched and the selection of the next rows is correctly loaded and then shuffled, meaning there are no duplicates.使用 ajax 加载时,前端的行仍然可以在分页器中正常工作,因为集合没有被触及,并且下一行的选择被正确加载然后打乱,这意味着没有重复。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM