您的位置:首页 > 编程语言 > PHP开发

Laravel 手动分页实现详解

2017-08-11 18:44 811 查看
因为Laravel 手册上对于手动分页的描述并不详细,这里大概说说笔者的实现方法

场景说明

在写一个大分类下所有文章的列表页时,笔者把取出来的数据都转换成了数组,这里为了清晰的说明并没有使用Repository来进行封装。

/**
* 当parent_id为0时为顶级分类,这时候会把顶级分类
* 下的文章以及子分类下的文章都放到一个数组中
* 当parent_id不为0时取出对应分类下的文章
*/
Cate::find($id)->first()->parent_id == 0 ?
$listInfo = array_merge(Cate::with('articles')->where('id',$id)->get()->toArray(),
Cate::with('articles')->where('parent_id',$id)->get()->toArray())
:
$listInfo = Cate::with('articles')->where('id',$id)->get()->toArray();
1
2
因为转换成数组的缘故,不能直接使用
paginate()
方法来实现分页。

手动实现分页

/**
* ArticleListController.php
*
*/

<?php

namespace App\Http\Controllers;

use App\Cate;
use Illuminate\Pagination\LengthAwarePaginator;

class ArtlistController extends AppController
{
public function index($id)
{
Cate::find($id)->first()->parent_id == 0 ?
$listInfo = array_merge(Cate::with('articles')->where('id',$id)->get()->toArray(),
Cate::with('articles')->where('parent_id',$id)->get()->toArray())
:
$listInfo = Cate::with('articles')->where('id',$id)->get()->toArray();
$count = 0;
foreach ($listInfo as $item) {
$count += count($item['articles']);
}
$paginator = new LengthAwarePaginator($listInfo,$count,4);
$categories = $this->parent();
return view('article.list',['categories' => $categories,'listInfo' => $listInfo,'paginator' => $paginator]);
}
}
1
2
以上的关键代码如下

$count += count($item['articles'])
把分页数据的
总数
求出来

$paginator = new LengthAwarePaginator($listInfo,$count,4)
这里的参数依次是
分页的数据
,
分页数据的总数
,
每页多少条
。第三个参数可以直接写到conf文件中来灵活调整。

/**
* list.blade.php
*
*/

{!! $paginator->render() !!}

然后是前端模板中的写法。Done!

查看更多,请访问我的博客

by vampirebitter
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: