Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create pagination using KnexJS + PG

What would be the most optimal way to create pagination using knexjs? I sincerily have no idea how to do pagination in general. Below my code:

router.get("/", (req, res) => {
  db.select("*")
    .from("site.site_product")
    .offset(0)
    .limit(10)
    .then(data => {
      res.render("inventory/site_product", { data: data });
    });
});

Any help will be appreciated.

Thank you

like image 543
Blinhawk Avatar asked Aug 26 '26 11:08

Blinhawk


1 Answers

Try This

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
        });
    });
});
like image 61
Ayon Saha Avatar answered Aug 28 '26 02:08

Ayon Saha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!