18

Does anyone have any ideea how to write an OR logic like the ' || ' operator in JS I tried inside my knex to do it like that ->

knex('something')
  .where({ state: BOOKING_STATE.ACCEPTED } || { state: BOOKING_STATE.WAITING_LIST})

however it fails and i can't find anything about it in the docs

1
  • Can you post your full knex query? Commented Dec 12, 2018 at 21:31

3 Answers 3

60

If you check the documentation for where clauses with Knex, you'll see a grouped chain where, if you're trying to have multiple where clauses, but only want to or the two you listed, then something like this would work.

knex('something')
.where(function() {
  this.where('state', BOOKING_STATE.ACCEPTED ).orWhere('state', BOOKING_STATE.WAITING_LIST)
})
.andWhere('something', something_else)
...;
2
  • 4
    Can we get this as the accepted answer? This is the solutions we needed. Commented Mar 4, 2022 at 22:16
  • this also worked for me: .where( (myVal) => { myVal.where..... because this does not appear to work inside of the arrow function, according to: github.com/knex/knex/issues/2028 Commented Aug 6, 2023 at 20:28
9

You should be able to use a combination of where() and orWhere():

knex('something')
  .where({ state: BOOKING_STATE.ACCEPTED })
  .orWhere({state: BOOKING_STATE.WAITING_LIST })
2

As you can see on the Knex.js Documentation, it has functions for where, andWhere and orWhere. So you can easily chain your WHERE queries by calling

knex('something')
    .where({ state: BOOKING_STATE.ACCEPTED })
    .orWhere({ state: BOOKING_STATE.WAITING_LIST })

You can also use:

knex.select('some_field').from('some_table')
.where({ state: BOOKING_STATE.ACCEPTED })
.orWhere({ state: BOOKING_STATE.WAITING_LIST })

Not the answer you're looking for? Browse other questions tagged or ask your own question.