第9章 · 初心者向け
Pagination
件数が多いときは、ページに分けて少しずつ表示します。
1. ページングとは
結果を「1ページあたり○件」に分けて見せる仕組み
たとえ
本の目次や、検索結果の「1 2 3 …」ボタンです。
2. なぜPaginationが必要なのか
1万件を一度に出すと、遅いし読めません。10件ずつにすると快適です。
3. paginate()
$todos = $this->paginate($this->Todos->find());
$this->set(compact('todos'));
4. 件数設定
public array $paginate = [
'limit' => 10, // 1ページ10件
];
5. 並び順
public array $paginate = [
'limit' => 10,
'order' => ['Todos.id' => 'desc'],
];
6. 検索+Pagination
先に where で絞り、そのクエリを paginate に渡します。
$q = $this->request->getQuery('q');
$query = $this->Todos->find();
if ($q !== null && $q !== '') {
$query->where(['title LIKE' => '%' . $q . '%']);
}
$todos = $this->paginate($query);
7. View側でページリンクを表示
<?= $this->Paginator->prev('前へ') ?>
<?= $this->Paginator->numbers() ?>
<?= $this->Paginator->next('次へ') ?>
第9章 やってみよう
EXERCISE
- limit を 10 にする
- 検索語があるときだけ where する
- 前へ・次へリンクをViewに置く