Skip to content

Pagination

The ORM provides pagination through the query builder's paginate() method and the page<T> result struct.


The page<T> Struct

cpp
template<typename T>
struct page {
    std::vector<std::shared_ptr<T>> items;   // Rows for the current page
    int current_page = 1;                     // 1-indexed page number
    int per_page = 15;                        // Items per page
    std::int64_t total = 0;                   // Total matching rows
    int last_page = 0;                        // Total pages

    bool has_prev() const { return current_page > 1; }
    bool has_next() const { return current_page < last_page; }
};
FieldDescription
itemsModel instances for the current page.
current_pageCurrent page number (1-indexed).
per_pageNumber of items per page.
totalTotal number of rows matching the query.
last_pageTotal number of pages (computed as ceil(total / per_page)).

paginate(pool, cb, per_page, page_num) — Built-in Pagination

The preferred way to paginate. Automatically runs a count query and computes pagination metadata.

cpp
using namespace framework;
using namespace framework::database;

auto q = query<User>("users");
q->order_by("created_at", "DESC");

q->paginate(pool, [](auto ec, page<User> p) {
    if (!ec) {
        fmt::println("Page {} of {} ({} total items)",
            p.current_page, p.last_page, p.total);

        for (auto& user : p.items) {
            fmt::println("User: {}", user->name);
        }
    }
}, 15, 1);  // 15 per page, page 1
ParamDefaultDescription
poolDatabase connection pool.
cbCallback receives (error_code, page<T>).
per_page15Items per page.
page_num1Page number (1-indexed).

Manual Pagination with limit() / offset()

Use when you need full control over the pagination query.

cpp
int current_page = 1;
int per_page = 15;
int offset = (current_page - 1) * per_page;

auto q = query<User>("users");
q->order_by("created_at", "DESC");
q->limit(per_page);
q->offset(offset);

q->get(pool, [current_page, per_page](auto ec, auto results) {
    page<User> p;
    p.items = results;
    p.current_page = current_page;
    p.per_page = per_page;
    // You must run a separate count query for total/last_page
});