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
?
And note: The return knex( returns the Promise object to the caller, and the return dataArr returns the value to the caller's .
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.
Sequelize is an ORM that includes some query builder stuff; Knex is just a query builder, not an ORM.
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 .
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,
})
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 =
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With