简体   繁体   English

使用 Bookshelf.js 进行限制和偏移

[英]Limit and offset with Bookshelf.js

I am using the code below to fetch all results from a table:我正在使用下面的代码从表中获取所有结果:

Search.forge()
  .fetchAll()
  .then(function (collection) {
    res.json({error: false, data: collection.toJSON()});
  })

But I am going to need pagination and I thought I could do it with limit and offset, but so far I haven't found anything to provide me limit and offset options.但是我将需要分页,我认为我可以通过限制和偏移来做到这一点,但到目前为止我还没有找到任何可以为我提供限制和偏移选项的内容。

Is this even possible or do I have to build my query with Knex?这甚至可能还是我必须使用 Knex 构建我的查询?

Knex query builder should help, first you have to call collection.query() so that bookshelf tap into knex query builder 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());
            })

so knex query builder function -> http://knexjs.org/#Builder are now available for free所以 knex 查询构建器功能 -> http://knexjs.org/#Builder现在免费提供

This is how you can use pagination with Bookshelf.这就是如何在 Bookshelf 中使用分页。 Considering you have a Post model for example:考虑到您有一个 Post 模型,例如:

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

       })

But note that all the where Clauses must appear before the limit and orderBy clauses.但请注意,所有 where 子句都必须出现在 limit 和 orderBy 子句之前。

So far, there is no bookshelf.js solution for this.到目前为止,还没有 bookshelf.js 解决方案。 It can be easily achieved by using knex query builder.使用 knex 查询构建器可以轻松实现。

As of 6/2018, while core Bookshelf.js still doesn't include built-in support for pagination, there's a plugin to do exactly that .截至 2018 年 6 月,虽然核心 Bookshelf.js 仍然不包含对分页的内置支持,但有一个 插件可以做到这一点 It lets you express pagination either in a "page/pageSize" or "offset/limit" format depending on your needs, while under the hood it appears to make use of knex's built-in offset and limit capabilities on queries.它允许您根据需要以“page/pageSize”或“offset/limit”格式表示分页,而幕后,它似乎利用 knex 的内置偏移和查询限制功能。 Code sample:代码示例:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM