2016-09-20 67 views
2

我正在將get數組中的id數組傳遞給knex whereIn函數,但它們正在丟失。數組沒有傳遞給knex中的查詢

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

我將它們映射到整數的查詢。控制檯日誌...

[ 77, 66 ] 

但調試後查詢作爲...

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

有什麼我錯過了?

+0

其實,我現在在這些值是有綁定看到,但是,仍然字符串。 綁定:['77','66','1','100'], – latitudehopper

回答

2

值顯示爲字符串,因爲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]) 
}