Use operators 'like` or 'greater than' in Knex query with object syntax

Hedge picture Hedge · Jul 3, 2016 · Viewed 8.5k times · Source

I'm using JSON objects to build Knex queries like this:

{where: {id: '5'}

How can I use the same query format (object syntax) with operators like like or greater than ?

Answer

Artur Carvalho picture Artur Carvalho · Mar 14, 2017

You can use where/andWhere. The code below shows an update that only happens if the user_id = userId and book_reference = bookName and if result < res.

knex('user_books')
    .where({
      user_id: userId,
      book_reference: bookName
    })
    .andWhere('result', '<', res)
    .update({
      'updated_at': bookshelf.knex.raw('CURRENT_TIMESTAMP'),
      'text_done': true,
    })