Bli*_*awk 3 pagination node.js
使用 knexjs 创建分页的最佳方法是什么?我真的不知道如何做一般的分页。在我的代码下面:
router.get("/", (req, res) => {
db.select("*")
.from("site.site_product")
.offset(0)
.limit(10)
.then(data => {
res.render("inventory/site_product", { data: data });
});
});
Run Code Online (Sandbox Code Playgroud)
任何帮助将不胜感激。
谢谢
尝试这个
router.get("/", (req, res) => {
var reqData = req.query;
var pagination = {};
var per_page = reqData.per_page || 10;
var page = reqData.current_page || 1;
if (page < 1) page = 1;
var offset = (page - 1) * per_page;
return Promise.all([
db.count('* as count').from("site.site_product").first(),
db.select("*").from("site.site_product").offset(offset).limit(per_page)
]).then(([total, rows]) => {
var count = total.count;
var rows = rows;
pagination.total = count;
pagination.per_page = per_page;
pagination.offset = offset;
pagination.to = offset + rows.length;
pagination.last_page = Math.ceil(count / per_page);
pagination.current_page = page;
pagination.from = offset;
pagination.data = rows;
res.render("inventory/site_product", {
data: pagination
});
});
});
Run Code Online (Sandbox Code Playgroud)
我使用knex-paginate这使得 PG 分页变得轻而易举。
以下是尝试的步骤:
npm install knex-paginate -s
const { attachPaginate } = require('knex-paginate');
attachPaginate();
Run Code Online (Sandbox Code Playgroud)
router.get("/paginated-results", (req, res) => {
const page = req.query.page;
return knex("artists").paginate({
perPage: 10,
currentPage: page
}).then(results => {
res.json(results)
})
})
Run Code Online (Sandbox Code Playgroud)
http://localhost:5000/paginated-results?page=2
归档时间: |
|
查看次数: |
5161 次 |
最近记录: |