Constraint and offset with Bookshelf.js

I am using the below code to get all results from a table:

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

      

But I would need pagination and thought I could do it with constraint and offset, but so far I haven't found anything to provide me with options for constraint and offset.

Is this possible or do I need to build my query with Knex?

+3


source to share


3 answers


There is no bookshelf.js solution for this yet. This can be easily achieved with the knex query builder.



0


source


The Knex query builder should help, you must first call the collection.query()

bookshelf to click on the query chain builder

  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 the bucket builder function -> http://knexjs.org/#Builder is now available for free

+7


source


This is how you can use bookshelf pagination. If you have a Post model like:

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

       })

      

But please note that all offers that must appear before the limit and OrderBy.

+1


source







All Articles