esanz91
esanz91

Reputation: 893

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) {
    ...
  });

Upvotes: 11

Views: 10387

Answers (3)

Rhys van der Waerden
Rhys van der Waerden

Reputation: 3847

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' }
})

Upvotes: 12

black21jack
black21jack

Reputation: 71

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();

Upvotes: 2

Salar
Salar

Reputation: 5509

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]);
                    });
                })

Upvotes: 13

Related Questions