繁体   English   中英

如何在 Laravel 5 中对合并的集合进行分页?

[英]How can I paginate a merged collection in Laravel 5?

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

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

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 模型和数据库查询,而不是集合。

你是对的。 但是需要一个用于集合的分页器功能。 页面

句法:

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);
}

如果您想使用 LengthAwarePaginator 只需实例化一个。 如上一个答案的评论中所述,您必须为此设置路径。 在实例化分页器之前,您还需要确保解析“currentPage”并设置要返回的项目。 这一切都可以在实例化之前/在实例化时完成。 所以一个函数可能看起来像:

function paginateCollection($collection, $perPage, $pageName = 'page', $fragment = null)
{
    $currentPage = \Illuminate\Pagination\LengthAwarePaginator::resolveCurrentPage($pageName);
    $currentPageItems = $collection->slice(($currentPage - 1) * $perPage, $perPage);
    parse_str(request()->getQueryString(), $query);
    unset($query[$pageName]);
    $paginator = new \Illuminate\Pagination\LengthAwarePaginator(
        $currentPageItems,
        $collection->count(),
        $perPage,
        $currentPage,
        [
            'pageName' => $pageName,
            'path' => \Illuminate\Pagination\LengthAwarePaginator::resolveCurrentPath(),
            'query' => $query,
            'fragment' => $fragment
        ]
    );

    return $paginator;
}

您可以在Providers/AppServiceProvider 中为 Collection 添加以下代码。

    // Enable pagination
    if (!Collection::hasMacro('paginate')) {

        Collection::macro('paginate', 
            function ($perPage = 15, $page = null, $options = []) {
            $page = $page ?: (Paginator::resolveCurrentPage() ?: 1);
            return (new LengthAwarePaginator(
                $this->forPage($page, $perPage)->values()->all(), $this->count(), $perPage, $page, $options))
                ->withPath('');
        });
    }

然后,您可以从 Collection 调用 paginate,就像 Eloquent 模型一样。 例如

$pages = collect([1, 2, 3, 4, 5, 6, 7, 8, 9])->paginate(5);

您可以尝试对两个集合进行分页并将它们合并。 您可以在文档api 中找到有关分页的更多信息。 这是手动创建自己的分页器的示例...

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

我在下面包含了 PaginationMerger 类。

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;
    }
}

分页集合的最佳方式:

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

       /*
         * use Illuminate\Support\Collection;
         * use Illuminate\Pagination\LengthAwarePaginator;
         *
         * 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-从此以后,您可以像代码一样对所有集合进行分页

$people->paginate(5)

我不得不在我正在从事的项目中处理类似的事情,在其中一个页面中,我必须显示两种类型的出版物,这些出版物created_at字段进行分页排序 就我而言,它是一个Post模型和一个Event模型(以下简称出版物)。

唯一的区别是我不想从数据库中获取所有出版物然后对结果进行合并和排序,你可以想象如果我们有数百个出版物会引起性能问题。

所以我发现对每个模型进行分页会更方便,然后才对它们进行合并和排序。

所以这就是我所做的(基于之前发布的答案和评论)

首先让我向您展示“我的解决方案”的简化版本,然后我将尽可能多地解释代码。

use App\Models\Post;
use App\Models\Event;
use App\Facades\Paginator;


class PublicationsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $events       = Event::latest()->paginate(5);
        $posts        = Post::latest()->paginate(5);

        $publications = Paginator::merge($events, $posts)->sortByDesc('created_at')->get();

        return view('publications.index', compact('publications'));
    }
}

你现在已经猜到了,门面分页器负责合并和排序我的分页器( $events$posts

为了使这个答案更加清晰和完整,我将向您展示如何创建自己的 Facade。

你可以选择把你自己的外墙放在你喜欢的任何地方,我个人选择把它们放在 app 文件夹下的 Facades 文件夹中,就像这棵树所示。

+---app
|   +---Console
|   +---Events
|   +---Exceptions
|   +---Exports
|   +---Facades
|   |   +---Paginator.php
|   |   +---...
|   +---Http
|   |   +---Controllers
.   .   +---...
.   .   .

将此代码放在app/Facades/Paginator.php

namespace App\Facades;

use Illuminate\Support\Facades\Facade;

class Paginator extends Facade
{
    /**
     * Get the registered name of the component.
     *
     * @return string
     */
    protected static function getFacadeAccessor()
    {
        return 'paginator';
    }
}

有关更多信息,您可以查看Facades 的工作原理

接下来,paginator绑定到服务容器,打开app\\Providers\\AppServiceProvider.php

namespace App\Providers;

use App\Services\Pagination\Paginator;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        $this->app->bind('paginator', function ($app) {

            return new Paginator;
        });
    }
}

有关更多信息,您可以查看启动方法

我的分页器类位于app/Services/Pagination/文件夹下。 同样,您可以将课程放在任何您喜欢的地方。

namespace App\Services\Pagination;

use Illuminate\Support\Arr;
use InvalidArgumentException;
use Illuminate\Support\Collection;
use Illuminate\Pagination\LengthAwarePaginator;

class Paginator
{
    /**
     * All of the items being paginated.
     *
     * @var \Illuminate\Support\Collection
     */
    protected $items;

    /**
     * The number of items to be shown per page.
     *
     * @var int
     */
    protected $perPage;

    /**
     * The total number of items before slicing.
     *
     * @var int
     */
    protected $total;

    /**
     * The base path to assign to all URLs.
     *
     * @var string
     */
    protected $path = '/';


    /**
     * Merge paginator instances
     *
     * @param  mixed $paginators
     * @param  bool  $descending
     * @return \Illuminate\Pagination\LengthAwarePaginator
     */
    function merge($paginators)
    {
        $paginators = is_array($paginators) ? $paginators : func_get_args();

        foreach ($paginators as $paginator) {
            if (!$paginator instanceof LengthAwarePaginator) {
                throw new InvalidArgumentException("Only LengthAwarePaginator may be merged.");
            }
        }

        $total   = array_reduce($paginators, function($carry, $paginator) {

            return $paginator->total();
        }, 0);

        $perPage = array_reduce($paginators, function($carry, $paginator) {

            return $paginator->perPage();
        }, 0);

        $items   = array_map(function($paginator) {

            return $paginator->items();

        }, $paginators);

        $items         = Arr::flatten($items);

        $items         = Collection::make($items);

        $this->items   = $items;
        $this->perPage = $perPage;
        $this->total   = $total;

        return $this;
    }

    /**
     * Sort the collection using the given callback.
     *
     * @param  callable|string  $callback
     * @param  int  $options
     * @param  bool  $descending
     * @return static
     */
    public function sortBy($callback, $options = SORT_REGULAR, $descending = false)
    {
        $this->items = $this->items->sortBy($callback, $options, $descending);

        return $this;
    }

    /**
     * Sort the collection in descending order using the given callback.
     *
     * @param  callable|string  $callback
     * @param  int  $options
     * @return static
     */
    public function sortByDesc($callback, $options = SORT_REGULAR)
    {
        return $this->sortBy($callback, $options, true);
    }

    /**
     * Get paginator
     *
     * @return \Illuminate\Pagination\LengthAwarePaginator
     */
    public function get()
    {
        return new LengthAwarePaginator(
            $this->items,
            $this->total,
            $this->perPage,
            LengthAwarePaginator::resolveCurrentPage(),
            [
                'path' => LengthAwarePaginator::resolveCurrentPath(),
            ]
        );
    }
}

肯定有改进的空间,所以如果你看到需要改变的东西,请在此处发表评论或在twitter 上联系我。

尝试跟随。

$arr = $pets->toArray();
$paginator->make($arr, count($arr), $perPage);

您可以像下面这样更改它:

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

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


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

似乎分页不再是laravel 8集合的一部分,所以我使用了 laravel 的Illuminate\\Pagination\\Paginator类来对数据进行分页,但是是一个问题,分页相关信息正在通过分页更新,但数据没有分页根本!

发现问题了,laravel的Paginator类没有正确对数据进行分页,可以查看类的原始方法。

/**
 * Set the items for the paginator.
 *
 * @param  mixed  $items
 * @return void
 */
protected function setItems($items)
{
    $this->items = $items instanceof Collection ? $items : Collection::make($items);

    $this->hasMore = $this->items->count() > $this->perPage;

    $this->items = $this->items->slice(0, $this->perPage);
}

因此,我构建了自己的Paginator类并从 laravel 的Paginator类扩展了它,并解决了我在下面向您展示的问题。

use Illuminate\Support\Collection;

class Paginator extends \Illuminate\Pagination\Paginator
{
    /**
     * Set the items for the paginator.
     *
     * @param  mixed  $items
     * @return void
     */
    protected function setItems($items)
    {
        $this->items = $items instanceof Collection ? $items : Collection::make($items);

        $this->hasMore = $this->items->count() > ($this->perPage * $this->currentPage);

        $this->items = $this->items->slice(
            ($this->currentPage - 1) * $this->perPage,
            $this->perPage
        );
    }
}

类的用法如下

(new Paginator(
    $items,
    $perPage = 10,
    $page = 1, [
        'path' => $request->url(),
    ]
))->toArray(),

我的数据分页现在工作正常。

我希望这对你有用。

use Illuminate\Support\Collection;

$collection = new Collection;

$collectionA = ModelA::all();
$collectionB = ModelB::all();

$merged_collection = $collectionA->merge($collectionB);

foreach ($merged_collection as $item) {

    $collection->push($item);
}

$paginated_collection = $collection->paginate(10);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM