LoginSignup
15
15

More than 5 years have passed since last update.

ORM + Pagination で、ページネーションする

Posted at

DBにあるデータを一覧する場合、ページネーションする必要がある。
ORMとPaginationを使用する場合は、以下のような処理の流れになると思う。

  1. ORMデータの総数を取得する(Paginationに渡すため)
  2. Paginationインスタンスをforge
  3. ORMで現在のページを取得する(Paginationのメソッドからlimitとoffsetを設定)

このように、
ORM -> Pagination -> ORM
のようにモジュールを使用するので、
以下のようにORMはメソッドチェーンでやると楽。

fuel/app/classes/controller/user.php
public function action_index()
{
    // カテゴリ1の総数を取得する。
    $query =
       Model_User::query()->where('category_id', 1);
    $total_items = $query->count();

    // Paginationインスタンスを生成
    $pagination = Pagination::forge('users', [
        'total_items' => $total_items,
        'per_page'    => 20,
        'uri_segment' => 'page',
    ]);
    $stash['pagination'] = $pagination;

    // 現在のページのユーザーのリストを取得
    $stash['users'] =
        $query
        ->order_by('created_by', 'desc')
        ->limit($pagination->per_page)
        ->offset($pagination->offset)
        ->get();

    ...
}
15
15
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
15