English
Pagination
Sutando has inbuilt support for offset-based pagination. You can paginate the results of a query by chaining the paginate
method.
The paginate
method accepts the rows to fetch as the first argument and the page number as the second argument. Internally, we execute an additional query to count the total number of rows.
Basic Usage
js
const users = await db.table('users')
.where('vote', '>', 1)
.paginate(15, 2); // Paginator
const users = await User.query()
.where('vote', '>', 1)
.paginate(15); // Paginator
const users = await db.table('users')
.where('vote', '>', 1)
.forPage(2, 15)
.get(); // Array
const users = await User.query()
.where('vote', '>', 1)
.forPage(1, 15)
.get(); // Collection
users.map(user => {
//
});
The paginate
method returns an instance of the Paginator
. It holds the meta data for the pagination, alongside the fetched rows.
Each paginator instance provides additional pagination information via the following methods:
Method | Description |
---|---|
paginator.count() | Get the number of items for the current page. |
paginator.currentPage() | Get the current page number. |
paginator.hasMorePages() | Determine if there are more items in the data store. |
paginator.items() | Get the items for the current page. |
paginator.lastPage() | Get the page number of the last available page. |
paginator.perPage() | The number of items to be shown per page. |
paginator.total() | Determine the total number of matching items in the data store. |
Serializing to Object/JSON
You can also serialize the paginator results to Object/JSON by calling the toData
or toJson
method. It returns the key names in snake_case by default. However, you can pass a naming strategy to override the default convention.
JSON
{
"total": 45,
"per_page": 15,
"current_page": 1,
"last_page": 3,
"count": 15,
"data": [
{
// Record...
},
{
// Record...
}
],
}