Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use 'and' with 'on' condition of joins in knex

Tags:

mysql

knex.js

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?

like image 892
kamlesh Avatar asked Mar 14 '16 14:03

kamlesh


People also ask

How does KNEX connect to database?

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);

What is KNEX query?

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.


1 Answers

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')]);
like image 138
SimoAmi Avatar answered Nov 12 '22 05:11

SimoAmi