Laravel 5.4的LengthAwarePaginator

18

我脑子突然卡住了。非常感谢任何想要帮助我的人。

这是 Laravel 5.4 中的 LengthAwarePaginator。

这里是代码。

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

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

根据 LengthAwarePaginator 构造函数。这是参考资料。

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

这是截图。

在此输入图片描述

我错在哪里了?谢谢。

2个回答

41

当手动创建分页器时,您需要自己切割结果集。分页器的第一个参数应该是所需的结果页,而不是整个结果集。

分页文档中:

当手动创建分页器实例时,您应该手动“切割”传递给分页器的结果数组。如果您不确定如何做到这一点,请查看PHP的array_slice函数。

我建议使用Collection来帮助处理:

// ...

$collection = collect($collection);

$page = 1;
$perPage = 10;

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

谢谢...我已经明白了,这是链接:http://psampaz.github.io/custom-data-pagination-with-laravel-5/。 - Rbex
@Rbex 那篇文章有点老了。我用一些新的集合代码更新了我的答案(即forPage()方法)。 - patricus
1
比链接容易多了。无论如何,非常感谢你。你是个超级巨星! - Rbex
这真是个好发现 - 我已经花了几个小时在这上面苦苦挣扎。非常感谢 @patricus! - FullStackOfPancakes
天啊,我已经寻找这个东西好几年了! - Tudor-Radu Barbu

1

为了避免在表格中进行重复选择并计算总数,我们无法使用模型分页。

use Illuminate\Pagination\LengthAwarePaginator;

在你的控制器函数中。
if(!isset($input["total"])){ //initial request
         $total = //Find the total only one time.
         $request->request->add(['total' => $total]); //Add it in the request so that we can print it in blade 
}else
         $total = $input["total"];  //After initial request

$currentPage = LengthAwarePaginator::resolveCurrentPage(); //page variable from GET or POST
$perPage = 30; //Page Length 
$offset = ($currentPage - 1) * $perPage; //find the offset to pass in query
$specificRecords = /*Collect specific page records in array 
if mysql then Select * from table limit $perPage offset $offset 
if ms sql then OFFSET {$offset} ROWS FETCH NEXT {$perPage} ROWS ONLY */
$records = new LengthAwarePaginator($specificRecords,$total,$perPage,Null,[ "path" => "/pagepath" ]);

在Blade模板中:
<center>{{$records->appends(Request::except([ 'page','_token' ]))->links()}}</center>

检查页面标签中的Page和total变量,确保您将该页面添加到了except列表中 :)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接