I am trying to generate a query like:
select ifnull(t1.name, ‘default’) as name
from tab1 as t1
left join tab2 as t2
on t1.id=t2.id and t2.code=“someValue”
I wrote this in knex:
var query = knex().from(’tab1’).join(’tab2', function() {
this.on('tab1.id', '=', 'tab2.id').andOn('tab2.code', '=', 'someValue')
},
‘left')
.column([
knex.raw(‘IFNULL(tab1.name, "no name") as name')
]);
This does not execute as it treats 'someValue' as a column. How can I apply 'and' condition in this case?
Connecting Knex with Postgres We specify the connection parameters for Postgres and point Knex to connect to the pg client. const db = require("knex")({ client: "pg", connection: { host: "localhost", user: "postgres", password: "", database: "knex-test" } }); app. set("db", db);
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.
Not well documented but you can now use onVal
, and any of its and / or variants.
So, instead of
.on('tab2.code', '=', knex.raw('?', ['someValue']))
You can simply write:
const query = knex()
.from('tab1')
.join('tab2', function() {
this.on('tab1.id', '=', 'tab2.id')
this.andOnVal('tab2.code', '=', 'someValue')
}, 'left')
.column([knex.raw('IFNULL(tab1.name, "no name") as name')]);
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