db.raw with more than one paremter with knex

10.6k views Asked by At

This currently works in knex:

knex.raw('select * from users where id = ?', [1])

I am trying to use more than one value as parameters, repeating some of them. Something like this:

knex.raw('select * from users where id = 1? and name = 2? and firstName = 2?', [1, 'someName'])

How can I achieve that?

2

There are 2 answers

0
Sombriks On BEST ANSWER

you can do something like this also:

var params = {x1:1,dude:10};
return knex.raw("select * from foo where x1 = :x1 and dude = :dude",params);

it's not the first example, but it's documented here.

3
Dr.Knowitall On

It looks like the obvious quick solution is to simply repeat your array elements.

knex.raw('select * from users where id = 1? and name = 2? and firstName = 3?', [1, 'someName', 1])

I don't know knex, but there's nothing wrong with this solution either.

EDIT

A different approach is to use simple string interpolation through a library like kiwi:

var interpolateObject = {
  id: 'some_id',
  name: 'some_name',
  firstName: 'some_first_name'
};

var query = Kiwi.compose(
   "select * from users where id = %{id} and name = %{name} and firstName = %{firstName}",
    interpolateObject
    );

knex.raw(query);

Checkout kiwi.js