简体   繁体   中英

Bookshelf.JS | How to use where and orWhere in query

BookshelfJS has the following example for using 'query':

model
  .query({where: {other_id: '5'}, orWhere: {key: 'value'}})
  .fetch()
  .then(function(model) {
    ...
  });

Is it okay to do the following:

var whereObj = {
  'key1':'value1',
  'key2':'value2'
};

model
  .query({where: whereObj, orWhere: {key: 'value'}})
  .fetch()
  .then(function(model) {
    ...
  });

For more complex queries, you can use this:

.query(function(qb) {
                    qb.select('*');
                    qb.where(function () {
                        this.where('attr1', 1);
                        this.where('attr2','in' , [1,2,3]);
                    });
                    qb.orWhere(function () {
                        this.where('attr1', 2);
                        this.where('attr2','in' , [4,5,6]);
                    });
                })

You have two options:

Use a callback

.query(function (qb) {
    qb.where(other_id, '5')
        .orWhere('key', 'value');
});

Use an object

.query({
    where: { other_id: '5' },
    orWhere: { key: 'value' }
})

Check out the bookshelf-eloquent extension which exposes many of the Knex.js functions directly on the bookshelf model. Your code would be simplified to something like this:

let result = await Model.where({other_id: 5}).orWhere('key', 'value').fetch();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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