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

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

问题描述

我合并了两个运行良好的查询结果:

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

$events1 = \App\Event::Where('valid_to','>=',$today)->orderByRaw('valid_to','ASC')->get();
$events2 = \App\Event::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 \Illuminate\Pagination\LengthAwarePaginator(
    $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 = \App\Event::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 = \App\Event::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天全站免登陆