如何在 Laravel 5 中对合并的集合进行分页? [英] How can I paginate a merged collection in Laravel 5?

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

问题描述

我正在创建一个流,其中包含两种类型的对象,BluePerson 和 RedPerson.为了创建流,我获取了所有两个对象,然后将它们合并到一个集合中.这样做之后,我需要对它们进行分页,但是 paginate 似乎是用于 eloquent 模型和数据库查询,而不是集合.我已经看到很多关于手动创建分页器的文档,尤其是在 API 中的文档很少(我什至找不到分页器类接受的参数.)

I am creating a stream which contains two types of objects, BluePerson and RedPerson. To create the stream, I fetch all of both objects, then merge them into one collection. After doing so, I need to paginate them, however paginate is for eloquent models and DB queries, and not collections, it seems. I have seen a lot about manually creating a paginator, but the documentation, especially in the API is sparse (I can't even seem to find the arguments the Paginator class accepts.)

如何对合并收藏的结果进行分页?

How can I paginate the results of merging my collections?

public function index()
{
    $bluePerson = BluePerson::all();
    $redPerson = RedPerson::all();

    $people = $bluePerson->merge($redPerson)->sortByDesc('created_at');


    return view('stream.index')->with('people', $people);
}

推荐答案

但是 paginate 似乎是用于 eloquent 模型和数据库查询,而不是集合.

however paginate is for eloquent models and DB queries, and not collections, it seems.

你说得对.但是需要一个用于集合的分页器功能.forPage

You are right. but there is ineed a paginator function for collections. forPage

Collection forPage(int $page, int $perPage)

示例:

休息很简单.

public function foo()
{
    $collection = collect([1,2,3,4,5,6,7,8,9,0]);
    $items = $collection->forPage($_GET['page'], 5); //Filter the page var
    dd($items);
}

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

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