Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array not being passed to query in knex

I am passing an array of ids from a get query to a knex whereIn function but they are going missing.

if(query.cols){
  var cols = query.cols.map(Number);
  console.log(cols)
  search.whereIn('collection_id', cols)
}

I am mapping them to Integers for the query. The console log is...

[ 77, 66 ]

But the debug shows the query as...

...and "collection_id" in (?, ?) 

What have I missed?

like image 778
latitudehopper Avatar asked Sep 20 '16 15:09

latitudehopper


1 Answers

The values show as strings because knex requires that arrays be passed as arguments within a containing array. From the documentation for raw bindings:

Note that due to ambiguity, arrays must be passed as arguments within a containing array.

knex.raw('select * from users where id in (?)', [1, 2, 3]);
// Error: Expected 3 bindings, saw 1

knex.raw('select * from users where id in (?)', [[1, 2, 3]])
Outputs:
select * from users where id in (1, 2, 3)

You can fix this by passing the cols array within an array itself:

if (query.cols) {
  var cols = query.cols.map(Number);
  console.log(cols)
  search.whereIn('collection_id', [cols])
}
like image 178
gnerkus Avatar answered Sep 23 '22 09:09

gnerkus