Paginate分页
// ORM 默认分页
$students=Student::paginate(5);
//显示
$students->render();
// 使用简单模板 - 只有 "上一页" 或 "下一页" 链接
Student::where('cars', 2)->simplePaginate(15);
// 手动分页
$item //手动查询到的数据
$total //所有符合条件的数据总数量
$perPage //每个页面,数据显示的条数
Paginator::make($items, $totalItems, $perPage);
手动分页详解
laravel自带的分页功能十分强大,只不过,在使用 groupBy 语句的分页操作时,无法由 Laravel 有效执行。如果你需要在一个分页结果集中使用groupBy,建议你查询数据库并手动创建分页器。
//控制器代码
use Illuminate\Support\Facades\DB;
use Illuminate\Pagination\LengthAwarePaginator;
class IndexController extends Controller
{
//测试查询数据库并手动创建分页器
public function paginationTest(Request $request){
$perPage = 5;
$page = $request->input("page",1)-1;
$total = DB::table("person")
->groupBy()
->count();
$items = DB::table("person")
->groupBy()
->skip($page*$perPage)
->take($perPage)
->get();
//$items = array_slice($users, ($current_page-1)*$perPage, $perPage);
//5.4版本
$person = new LengthAwarePaginator($items, $total,$perPage);
//设置baseUrl的方法
$person->withPath("pagTest");
//5.4版本之前
$paginator =new LengthAwarePaginator($items, $total, $perPage, $currentPage, [
'path' => Paginator::resolveCurrentPath(),
'pageName' => 'page',
]);
return view("index.paginationTest",['person' => $person]);
}
}
//blade
普通分页
{!!{ $paginator->render() }!!}
携带查询条件
{!! $paginator->appends(request()->input())->render() !!}
底层详解
LengthAwarePaginator构造函数,代码如下
/**
* Create a new paginator instance.
*
* @param mixed $items
* @param int $total
* @param int $perPage
* @param int|null $currentPage
* @param array $options (path, query, fragment, pageName)
* @return void
*/
publicfunction __construct($items,$total,$perPage,$currentPage=null,array$options= [])
{
foreach ($optionsas$key=>$value) {
$this->{$key} =$value;
}
$this->total=$total;
$this->perPage=$perPage;
$this->lastPage= (int)ceil($total/$perPage);
$this->path=$this->path!='/'?rtrim($this->path,'/') :$this->path;
$this->currentPage=$this->setCurrentPage($currentPage,$this->pageName);
$this->items=$itemsinstanceofCollection ?$items: Collection::make($items);
}
网友评论