合并两个集合后如何制作分页?

时间:2017-03-11 15:17:35

标签: laravel laravel-5.4

我使用标准方法进行分页:

$ann = Ann::get()->orderBy('id', 'desc')->paginate($limit);

我将$ann与另一个集合合并后:

$ann = $ann->merge($ann_subscribed);
            $ann = $ann->all();

结果我得到$ann = $ann->all();没有分页

1 个答案:

答案 0 :(得分:1)

1- 将此添加到 \app\Providers\AppServiceProvider 中的启动功能

 /**
         * Paginate a standard Laravel Collection.
         *
         * @param int $perPage
         * @param int $total
         * @param int $page
         * @param string $pageName
         * @return array
         */
        Collection::macro('paginate', function($perPage, $total = null, $page = null, $pageName = 'page') {
            $page = $page ?: LengthAwarePaginator::resolveCurrentPage($pageName);
            return new LengthAwarePaginator(
                $this->forPage($page, $perPage),
                $total ?: $this->count(),
                $perPage,
                $page,
                [
                    'path' => LengthAwarePaginator::resolveCurrentPath(),
                    'pageName' => $pageName,
                ]
            );
        });

2-以后所有收藏都可以这样分页

$ann = Ann::orderByRaw('id','DESC')->get();
$ann_merged = $ann->merge($ann_subscribed);
$ann_merged ->paginate(5);