如何获取knex / mysql中所有更新记录的列表

时间:2017-01-11 19:01:37

标签: mysql node.js knex.js

以下是我正在处理的查询:

  return knex('table')
    .returning('id')
    .where('boolean', false)
    .andWhere('fooID', foo.id)
    .update({
      boolean : true
    })
    .limit(num)
    .then(function(ids) {
      console.log('\nids');
      console.log(ids); //outputs num

ids现在包含3,即受影响的行数。有没有办法获得这3行的ID?我的印象是.returning()那样做了,但似乎没有。

1 个答案:

答案 0 :(得分:7)

Mysql数据库不支持returning语句,它只返回更新行http://dev.mysql.com/doc/refman/5.7/en/update.html的计数。

在您的情况下,您必须先查询要更新的行的ID,然后在事务中更新并获取它们。

像这样:

return knex.transaction(trx => {
  return trx('table')
    .select('id')
    .where('boolean', false)
    .andWhere('fooID', foo.id)
    .limit(num)
    .then(ids => {
      return trx('table').update({ boolean: true })
        .whereIn('id', ids)
        .then(() => {
          return trx('table').whereIn('id', ids);
        });
    });
});