How can I paginate a merged collection in Laravel 5?

后端 未结 7 1503
温柔的废话
温柔的废话 2020-12-02 14:31

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.

7条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-02 15:05

    You might try paginating both sets and merging them. You can find more information about pagination in the docs and the api. Here is an example of manually creating your own paginator...

    $perPage = 20;
    $blue = BluePerson::paginate($perPage / 2);
    $red = RedPerson::paginate($perPage - count($blue));
    $people = PaginationMerger::merge($blue, $red);
    

    I have included the PaginationMerger class below.

    use Illuminate\Pagination\LengthAwarePaginator;
    
    class PaginationMerger
    {
        /**
         * Merges two pagination instances
         *
         * @param  Illuminate\Pagination\LengthAwarePaginator $collection1
         * @param  Illuminate\Pagination\LengthAwarePaginator $collection2
         * @return Illuminate\Pagination\LengthAwarePaginator
         */
        static public function merge(LengthAwarePaginator $collection1, LengthAwarePaginator $collection2)
        {
            $total = $collection1->total() + $collection2->total();
    
            $perPage = $collection1->perPage() + $collection2->perPage();
    
            $items = array_merge($collection1->items(), $collection2->items());
    
            $paginator = new LengthAwarePaginator($items, $total, $perPage);
    
            return $paginator;
        }
    }
    

提交回复
热议问题