如何在 Laravel 中的 get() 之后对集合进行分页? [英] How to paginate a collection after get() in Laravel?

查看:20
本文介绍了如何在 Laravel 中的 get() 之后对集合进行分页?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对两个查询结果进行了合并,效果很好:

I have a merge on two query results which works fine:

$events1 = AppEvent::Where('valid_to','>=',$today)->orderByRaw('valid_to','ASC')->get();
$events2 = AppEvent::Where('valid_to','<',$today)>orderByRaw('valid_to','ASC')->get();
$events = $events1->merge($events2); 

现在我需要对这个新集合进行分页,并按照建议添加了这篇文章:

Now I need to paginate this new collection and as suggestted I added this piece:

$page = 1;
$perPage = 60;
$pagination = new IlluminatePaginationLengthAwarePaginator(
    $events->forPage($page, $perPage), 
    $events->count(), 
    $perPage, 
    $page
);

对于未来的读者,帕特里克斯的回答非常有效,我做到了.

For future readers, patricus's answer works great and I did that.

推荐答案

您在错误的对象上调用了 links()render().您已将分页器分配给 $pagination 变量.你应该打电话

You're calling links() and render() on the wrong object. You've assigned the paginator to the $pagination variable. You should be calling

$pagination->links()

$pagination->render()

此外,如果您想稍微清理一下,您可以修改您的查询,以便您只有一个查询并且不需要组合两个不同的结果集.您只需要先对日期比较的结果进行排序,然后对 valid_to 字段进行排序.

Also, if you'd like to clean this up a little bit, you can modify your query so that you only have one query and don't need to combine two different result sets. You just need to first order on the result of the date comparison, and then order on your valid_to field.

$events = AppEvent::orderByRaw('valid_to < ?', [$today])->orderBy('valid_to')->get();

日期比较将返回真/假结果.在 ASC 顺序中(未指定时默认),true 结果将在 false 结果之后,因此 valid_to 小于 的行$today(过期)将出现在 valid_to 大于或等于 $today 的行之后.

The date comparison will return a true/false result. In ASC order (default when not specified), true results will come after false results, so rows where the valid_to is less than $today (expired) will come after the rows where valid_to is greater than or equal to $today.

然后该结果集将由 valid_to 字段本身排序.这个查询为您提供与您手动合并的两个查询相同的结果.而且,当然,您可以只对这个查询进行分页:

That result set will then be ordered by the valid_to field itself. This one query gives you the same results as the two queries you've manually merged. And, of course, you can just paginate this one query:

$events = AppEvent::orderByRaw('valid_to < ?', [$today])->orderBy('valid_to')->paginate(60);

现在,您的 $events 对象是分页的,因此您需要使用 $events->links()$events->render().

Now, it is your $events object that is paginated, so you would want to use $events->links() and $events->render().

这篇关于如何在 Laravel 中的 get() 之后对集合进行分页?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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