1. 程式人生 > >關於laravel 得手動分頁問題

關於laravel 得手動分頁問題

array tor null etc this lar put 定義 Language

一般得分頁,我們只需要使用paginate方法,就可以簡單得搞定。但是遇到數組得組合情況呢?這個時候,就需要我們使用自定義分頁了。首先我們看下laravel得分頁方法源碼:

#vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php:480

public function paginate($perPage = null, $columns = [‘*‘], $pageName = ‘page‘, $page = null)
{
        $query = $this->toBase();

        $total = $query->getCountForPagination();

        $this->forPage(
            $page = $page ?: Paginator::resolveCurrentPage($pageName),
            $perPage = $perPage ?: $this->model->getPerPage()
        );

        return new LengthAwarePaginator($this->get($columns), $total, $perPage, $page, [
            ‘path‘ => Paginator::resolveCurrentPath(),
            ‘pageName‘ => $pageName,
        ]);
}
我們發現這個關鍵就是用了lengthAwarePaginator.
  LengthAwarePaginator的構造方法,如下:
public function __construct($items, $total, $perPage, $currentPage = null, array $options = [])
{
        foreach ($options as $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->lastPage);
        $this->items = $items instanceof Collection ? $items : Collection::make($items);
}


假定分頁得數組為:
[
  {
    "id": 9,
    "sys_id": 1,
    "org_id": 2,
    "user_id": 8,
    "papaer_id": 26,
  },
  {
    "id": 5,
    "sys_id": 1,
    "org_id": 2,
    "user_id": 8,
    "papaer_id": 26,
  },
  {
    "id": 1,
    "sys_id": 1,
    "org_id": 2,
    "user_id": 8,
    "papaer_id": 26,
  }
]
這裏一共3條數據,我們設定每頁顯示1個,一共3頁。
分頁調用
use Illuminate\Pagination\LengthAwarePaginator;
  use Illuminate\Pagination\Paginator;

  public function show(Request $request){
$perPage = 1; //每頁顯示數量
if ($request->has(‘page‘)) {
$current_page = $request->input(‘page‘);
$current_page = $current_page <= 0 ? 1 :$current_page;
} else {
$current_page = 1;
}
$item = array_slice($real, ($current_page-1)*$perPage, $perPage); //註釋1
$total = count($real);

$paginator =new LengthAwarePaginator($item, $total, $perPage, $current_page, [
‘path‘ => Paginator::resolveCurrentPath(), //註釋2
‘pageName‘ => ‘page‘,
]);
return response()->json([‘result‘=>$paginator])
}

  上面的代碼中的重點是$item,如果不做註釋1處理,得出的是所有7條數據。

  註釋2處就是設定個要分頁的url地址。也可以手動通過 $paginator ->setPath(‘路徑’) 設置。

  頁面中的分頁連接也是同樣的調用方式 {{ $paginator->render() }}

註:返回得數據格式大概如下所示:

"result": {
    "current_page": 3,
    "data": [
    {
      "id": 5,
      "sys_id": 1,
      "org_id": 2,
      "user_id": 8,
"papaer_id": 26
     }
], "from": null, "last_page": 2, "next_page_url": null, "path": "http://www.text.tld/examination/show", "per_page": 2, "prev_page_url": "http://www.text.tld/examination/show?page=2", "to": null, "total": 3 }


關於laravel 得手動分頁問題