【问题标题】:Laravel collection forPage removed sorting?Laravel 集合 forPage 移除排序?
【发布时间】:2017-02-15 10:58:43
【问题描述】:

我正在尝试使用长度感知分页器对集合进行分页,如下所示:

new LengthAwarePaginator($cases->forPage($request->get('page'), $per_page), $cases->count(), $per_page, $request->get('page'));

就在此之前,我正在对集合进行排序;

$cases->sortBy('inactive_percentage', SORT_REGULAR, 'desc');

但是我从分页器得到的结果不一样。我首先得到低不活跃百分比。如果我尝试 per_page 说 100 多于现有记录,则结果排序正确。

如何使用分页器来处理排序好的集合?

【问题讨论】:

  • 你真的需要forPage吗?我以为那是分页器的工作。
  • 如果我必须手动使用它,我想我会这样做

标签: php laravel pagination


【解决方案1】:

我还不能发布任何 cmets...大声笑试图让我的代表提高一点...

我遇到了手动分页器,结果我不得不自己对数组进行切片...根据文档:

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

我的手动数组分页控制器功能之一的示例(分页器处理底层数组...)

public function comments(){

        // DB::select returns an array, thus we have to build the paginator ourselves...
        $comm = DB::select('select bla bla bla...
                            order by c.approved ASC, c.id DESC ');

        // this basically gets the request's page variable... or defaults to 1
        $page = Paginator::resolveCurrentPage('page') ?: 1;

        // Assume 15 items per page... so start index to slice our array
        $startIndex = ($page - 1) * 15;

        // Length aware paginator needs a total count of items... to paginate properly
        $total = count($comm);

        // Eliminate the non relevant items...
        $results = array_slice($comm, $startIndex, 15);

        $comments =  new LengthAwarePaginator($results, $total, 15, $page, [
            'path' => Paginator::resolveCurrentPath(),
            'pageName' => 'page',
        ]);
        return view('backend/comments', compact('comments'));
    }

希望这会有所帮助...

【讨论】:

  • 是的,最后我不得不自己拼接,所以你的答案是正确的。谢谢
猜你喜欢
  • 2017-06-06
  • 2016-07-10
  • 2017-08-02
  • 1970-01-01
  • 2021-09-20
  • 2017-10-05
  • 1970-01-01
  • 2020-07-19
  • 2020-01-04
相关资源
最近更新 更多