Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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) {
    ...
  });
like image 864
esanz91 Avatar asked Aug 25 '15 22:08

esanz91


2 Answers

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]);
                    });
                })
like image 127
Salar Avatar answered Sep 26 '22 22:09

Salar


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();
like image 33
black21jack Avatar answered Sep 25 '22 22:09

black21jack