用 Bookshelf.js 限制和偏移

Limit and offset with Bookshelf.js

我正在使用下面的代码从 table:

中获取所有结果
Search.forge()
  .fetchAll()
  .then(function (collection) {
    res.json({error: false, data: collection.toJSON()});
  })

但是我需要分页,我想我可以用限制和偏移量来做到这一点,但到目前为止我还没有找到任何东西可以为我提供限制和偏移量选项。

这甚至可能吗,还是我必须使用 Knex 构建查询?

到目前为止,还没有 bookshelf.js 解决方案。它可以通过使用 knex 查询生成器轻松实现。

Knex 查询生成器应该有帮助,首先你必须调用 collection.query() 以便书架接入 knex 查询生成器

  Models.forge()
            .query(function(qb) {
                //qb is knex query builder, use knex function here 
                qb.offset(0).limit(10);
            })
            .fetchAll().then(function(result) {
                res.json(result.toJSON());
            })

因此 knex 查询生成器功能 -> http://knexjs.org/#Builder 现在免费提供

这就是您在 Bookshelf 中使用分页的方法。例如,考虑到您有一个 Post 模型:

    Post.query(function (qb) {
            qb.orderBy('id', 'DESC');
            qb.limit(20);
    }).fetchAll()
      .then(function (collection) {

       })

但注意所有where子句必须出现在limit和orderBy子句之前

截至 6/2018,虽然核心 Bookshelf.js 仍然不包括对分页的内置支持,但有一个 plugin to do exactly that. It lets you express pagination either in a "page/pageSize" or "offset/limit" format depending on your needs, while under the hood 它似乎利用了 knex 的内置偏移和限制查询能力。代码示例:

Search.forge()
  .fetchPage({ offset: 30, limit: 10 })
  .then(function (collection) {
    res.json({error: false, data: collection.toJSON()});
  })