lat*_*per 6 javascript node.js knex.js
我将一个来自get查询的id数组传递给knex whereIn函数但它们将丢失.
if(query.cols){
var cols = query.cols.map(Number);
console.log(cols)
search.whereIn('collection_id', cols)
}
Run Code Online (Sandbox Code Playgroud)
我将它们映射到整数以进行查询.控制台日志是......
[ 77, 66 ]
Run Code Online (Sandbox Code Playgroud)
但调试显示查询为...
...and "collection_id" in (?, ?)
Run Code Online (Sandbox Code Playgroud)
我错过了什么?
值显示为字符串,因为knex要求将数组作为包含数组中的参数传递.从原始绑定的文档:
请注意,由于含糊不清,数组必须作为参数传递到包含的数组中.
Run Code Online (Sandbox Code Playgroud)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])
}
Run Code Online (Sandbox Code Playgroud)
小智 5
根据原始参数绑定的 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]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2675 次 |
| 最近记录: |