数组没有被传递给查询
Array not being passed to query in knex
我正在传递一个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())
相关文章:
- 在mongoose中使用正则表达式在对象数组中进行查询搜索
- MongoDB嵌套对象数组后查询
- jQuery对象从html表中查询为两个一维数组,用于Chartist图表
- 使用查询将对象数组发布到asp.net-mvc控制器操作的正确方法是什么
- 数组数据排序类似mysql查询
- 基于其他属性查询多维数组属性
- 解析查询查找方法返回对象而不是数组
- angularjs $resource将查询资源列表转换为对象数组
- Jquery数组查询不起作用
- 使用Undercore.js查询数组
- JQuery的PHP查询数组变量
- 通过将$resource查询数组添加到AngularJS中另一个数组的底部来进行分页加载
- 如何查询数组中的元素
- MongoDB:查询数组上的浮点数范围
- 解析云查询数组包含值
- PHP 查询数组到 Javascript Google Maps 迭代器
- 在mongodb中使用Node js查询数组项
- 我们如何在mongodb的node js中查询数组元素
- 查询数组 JavaScript
- 在MongoDB中查询数组中的数组;更新如果存在,插入如果为空