【问题标题】:Array not being passed to query in knex数组未传递给 knex 中的查询
【发布时间】:2016-09-20 15:25:17
【问题描述】:

我将一个 id 数组从 get 查询传递到 knex whereIn 函数,但它们丢失了。

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

我将它们映射到整数以进行查询。控制台日志是...

[ 77, 66 ]

但调试显示查询为...

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

我错过了什么?

【问题讨论】:

  • 实际上,我现在在绑定中看到值在那里,但是仍然是字符串。绑定:['77','66','1','100'],

标签: javascript node.js knex.js


【解决方案1】:

这些值显示为字符串,因为knex 要求将数组作为包含数组中的参数传递。来自raw bindings 的文档:

请注意,由于不明确,数组必须作为包含数组中的参数传递。

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])
}

【讨论】:

    【解决方案2】:

    根据关于原始参数绑定的 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]
    

    【讨论】:

    • 嗯...这很奇怪,因为 ? 不是有效的 postgres 语法
    • @Madeo 这正是 knex 使用问号的原因。如果它是有效的 postgres 语法,那么 postgres 和 knex 之间会有干扰
    【解决方案3】:

    所有致谢@chiragsrvstv

    我用 whereRaw 代替 knex.row 是代码

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-30
      • 1970-01-01
      • 2019-02-05
      • 1970-01-01
      • 1970-01-01
      • 2021-03-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多