2016-06-24 21 views
1

我們正在使用的列名的數組中knex:KnexJS使用列的數組: 「處理廢品:ER_BAD_FIELD_ERROR:未知列」

knex 
     .select(["rowid", "accountid", "accountname"]) 
     .from("account") 
     .then(function (e, rows) { 
      callback(e, rows) 
    }) 

,並得到以下錯誤:

select `rowid,accountid,accountname` from `account` 

Unhandled rejection Error: ER_BAD_FIELD_ERROR: Unknown column 'rowid,accountid,accountname' in 'field list' 

顯然,列名稱數組已被轉換爲導致錯誤的字段字符串。使用單個字段可正常工作:

knex 
     .select("rowid", "accountid", "accountname") 
     .from('account') 
     .then(function (e, rows) { 
      callback(e, rows) 
    }) 

這是已知問題嗎?是否有一個解決方案使用「選擇」功能的數組?

+0

我可以知道爲什麼你需要通過數組查詢嗎?它是從其他函數傳遞的嗎? –

+0

我們將我們的字段保存在數據字典中。另外,knex文檔表明這是允許的:「select.select([* columns]) 創建一個select查詢,爲查詢創建一個可選的列數組,最終默認爲*,如果在查詢構建時沒有指定。選擇調用的響應將通過從數據庫中選擇的一組對象來解析。「 – ASA2

+0

它看起來像卡住了!一串字段不起作用,並且數組不起作用。有任何想法嗎? – ASA2

回答

1

我沒有使用knex 0.9.0測試並接受數組參數爲select而不抱怨:

knex. 
    select(['c1','t1','c2']). 
    from('sample'). 
    then(function(rows) { 
    console.dir(rows); 
    }); 
// console.dir output: 
// [ { c1: 22, t1: 'xx', c2: 33 }, 
// { c1: 422, t1: 'xxxx', c2: 77 } ] 

正如你可能已經注意到你的例子有一個問題,無論如何,then()不遵循共同的回調錯誤第一種方式(callback(error, result))但相反:then(success_callback, failure_callback),藍鳥提供了一種方便的方法catch()以避免失敗的呼叫。所以,你可能會改變你的代碼:

knex 
    .select(["rowid", "accountid", "accountname"]) 
    .from('account') 
    .then(function (rows) { 
    callback(null, rows) 
    }) 
    .catch(function (e) { 
    callback(e, null); 
    }); 

如果您還碰巧使用一個版本knex的,不允許列名的數組,你可以通過.apply()調用替換的直接調用,如:

knex 
    .select.apply(knex, ["rowid", "accountid", "accountname"]) 
    .from('account') 
    .then(function (rows) { 
    callback(null, rows) 
    }) 
    .catch(function (e) { 
    callback(e, null); 
    }); 
+1

這已解決。試飛錯誤! :) – ASA2