paginate分页及手动分页(laravel)

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

 

转载于:https://www.cnblogs.com/yunchuang96/p/7515244.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值