Geek Guy
Geek Guy

Reputation: 702

Dynamyc queries in knex

I am trying to implement unions that can dynamically take query strings or builder as parameters. See the code below:

function dynamicUnion(queryString||builder){
baseQuery.union(function () {
//I want to use query string or querybuilder  here instead.
     this.select('*').from('users').whereNull('first_name');
        })
     }

In the place of the line: this.select('*').from('users').whereNull('first_name'), I would like to implement something like: this.raw(queryString||builder) or any working alternative though I've not come across .raw() method when working with this keyword in that block.

I am implementing it this way since the select queries that are to be used in the union will will vary and it's efficient if passed dynamically.

Upvotes: 0

Views: 504

Answers (1)

Mikael Lepistö
Mikael Lepistö

Reputation: 19728

Sounds like a bug in knex that this.raw is not working in this case. Here is one way to pass raw query to union:

const Knex = require('knex');


const knex = Knex({
  client: 'mysql',
});

knex('foo').union(knex.raw('foo bar')).toSQL();

// outputs "select * from `foo` union foo bar"

https://runkit.com/embed/10boda0lt1it

Upvotes: 1

Related Questions