Laravel 5.4 LengthAwarePaginator

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43601095/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 15:50:59  来源:igfitidea点击:

Laravel 5.4 LengthAwarePaginator

laravel

提问by Rbex

My brain suddenly crashed on this one. Anyone care to help me is highly appreciated.

我的大脑突然在这个问题上崩溃了。任何愿意帮助我的人都非常感谢。

This is LengthAwarepaginator in laravel 5.4

这是 Laravel 5.4 中的 LengthAwarepaginator

Here is the code.

这是代码。

$collection = [];

            foreach ($maincategories->merchantCategory as $merchantCat) {

               foreach ($merchantCat->merchantSubcategory as $merchantSub) {

                   foreach($merchantSub->products as $products){

                        $collection[] = $products;
                   }
               }
            }

            $paginate = new LengthAwarePaginator($collection, count($collection), 10, 1, ['path'=>url('api/products')]);

            dd($paginate);

It displays perfectly but the problem is the items is 100. That's all my items and I specify it correctly. I need to display only 10.

它显示完美,但问题是项目是 100。这是我所有的项目,我正确指定了它。我只需要显示 10。

Base on LengthAwarePaginator constructor. Here is the reference.

基于 LengthAwarePaginator 构造函数。这是参考。

public function __construct($items, $total, $perPage, $currentPage = null, array $options = [])

Here is the screen shot.

这是屏幕截图。

enter image description here

在此处输入图片说明

Where did I go wrong? TY

我哪里做错了?泰

回答by patricus

When manually creating a paginator, you have to slice the result set yourself. The first parameter to the paginator should be the desired page of results, not the entire result set.

手动创建分页器时,您必须自己对结果集进行切片。分页器的第一个参数应该是所需的结果页面,而不是整个结果集。

From the pagination documentation:

分页文档

When manually creating a paginator instance, you should manually "slice" the array of results you pass to the paginator. If you're unsure how to do this, check out the array_slicePHP function.

手动创建分页器实例时,您应该手动“切片”传递给分页器的结果数组。如果您不确定如何执行此操作,请查看array_slicePHP 函数。

I would suggest using a Collectionto help out with this a little:

我建议使用 aCollection来帮助解决这个问题:

// ...

$collection = collect($collection);

$page = 1;
$perPage = 10;

$paginate = new LengthAwarePaginator(
    $collection->forPage($page, $perPage),
    $collection->count(),
    $perPage,
    $page,
    ['path' => url('api/products')]
);