KnexJS Using Array of Columns: "Unhandled rejection Error: ER_BAD_FIELD_ERROR: Unknown column"

KnexJS Using Array of Columns: "Unhandled rejection Error: ER_BAD_FIELD_ERROR: Unknown column"

我们在 knex 中使用列名数组:

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

这是一个已知问题吗?是否有将数组与 'select' 函数一起使用的解决方法?

我使用 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),使用 bluebird提供一种方便的方法 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);
  });