数组没有被传递给查询

Array not being passed to query in knex

本文关键字:查询 数组      更新时间:2023-09-26

我正在传递一个id数组从一个get查询到一个knex where函数,但他们正在丢失。

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

我将它们映射为查询的整数。控制台日志是…

[ 77, 66 ]

但是调试显示查询为…

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

我错过了什么?

编辑:
此解决方案适用于以前版本的Knex (v0.12.1)

原始绑定的当前文档可以在这里找到:https://knexjs.org/guide/raw.html#raw-parameter-binding

:
这些值显示为字符串,因为knex要求数组在包含数组中作为参数传递。原始绑定的文档:

注意,由于歧义,数组必须作为包含数组的参数传递。

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)

你可以通过在数组中传递cols数组来解决这个问题:

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

根据Knex文档关于原始参数绑定的说明,我们需要为数组中要绑定到查询的每个元素添加?:

由于数组绑定没有统一的语法,相反,您需要通过添加?直接在你的查询中。http://knexjs.org/Raw-Bindings

const myArray = [1,2,3]
knex.raw('select * from users where id in (' + myArray.map(_ => '?').join(',') + ')', [...myArray]);
// query will become: select * from users where id in (?, ?, ?) with bindings [1,2,3]

感谢@chiragsrvstv

代替knex。这里的代码是

const whereClause= [ 75, 76 ]

//if array length is 0 then have this
//`select * from "users" where id!=0`
     if(whereClause.length <= 0) {
            whereClause= [ 0 ]
        }
    
        console.log(  knex('users').whereRaw("id!="+whereClause.map(_ => '?').join(' and id!='), [...whereClause]).toString())