Laravel中针对集合进行分页

在开发的过程中,遇到过一些需求;需要在分页之前对数据进行一些调整(如:为每条数据增加一个属性「可根据此属性进行查询或筛选」),此时我想到的一个方案就是手动对查询出来的集合进行分页。

代码示例:

public function index(Request $request){
	//获取学生数据 并 为每一个学生数据增加一个自定义属性
	$students = Student::all()
	    ->each(function (Student $student){
	       return $student->customize_attr = 'test';
	    });
	// 对数据进行手动分页
	$per_page = $request->get('per_page',10); // 每页显示的条数
	$result = $this->paginateCollection($users, $per_page);

	return ApiResponse::Success($result);
}

/**
 * 自定义分页方法
 * @param $collection
 * @param $perPage
 * @param string $pageName
 * @param null $fragment
 * @return \Illuminate\Pagination\LengthAwarePaginator
 */
protected function paginateCollection($collection, $perPage, $pageName = 'page', $fragment = null)
{
    $currentPage = \Illuminate\Pagination\LengthAwarePaginator::resolveCurrentPage($pageName);
    $currentPageItems = $collection->slice(($currentPage - 1) * $perPage, $perPage)->values();
    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;
}
发布了15 篇原创文章 · 获赞 21 · 访问量 3489

猜你喜欢

转载自blog.csdn.net/qq_37868757/article/details/104635328
今日推荐