Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 ?

like image 477
Hedge Avatar asked Jul 03 '16 11:07

Hedge


People also ask

What does KNEX query return?

And note: The return knex( returns the Promise object to the caller, and the return dataArr returns the value to the caller's .

What is Knexjs?

Knex.js (pronounced /kəˈnɛks/) is a "batteries included" SQL query builder for PostgreSQL, CockroachDB, MSSQL, MySQL, MariaDB, SQLite3, Better-SQLite3, Oracle, and Amazon Redshift designed to be flexible, portable, and fun to use.

Is KNEX an ORM?

Sequelize is an ORM that includes some query builder stuff; Knex is just a query builder, not an ORM.

What is KNEX promise?

Promises. Promises are the preferred way of dealing with queries in knex, as they allow you to return values from a fulfillment handler, which in turn become the value of the promise. The main benefit of promises are the ability to catch thrown errors without crashing the node app, making your code behave like a .


2 Answers

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,
    })
like image 99
Artur Carvalho Avatar answered Sep 30 '22 12:09

Artur Carvalho


I don't think it's possible. Looking at the relevant source code of the query builder, it looks like:

_objectWhere(obj) {
  const boolVal = this._bool();
  const notVal = this._not() ? 'Not' : '';
  for (const key in obj) {
    this[boolVal + 'Where' + notVal](key, obj[key]);
  }
  return this;
}

Which basically calls the appropiate Where function with just two parameters (thus no operator, which means =)

like image 44
Jcl Avatar answered Sep 30 '22 10:09

Jcl