How to get a list of all updated records in knex / mysql

允我心安 提交于 2019-12-11 00:35:18

问题


Here's the query I'm working on:

  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 now contains 3, which is the number of affected rows. Is there any way to get the ids of those 3 rows? I was under the impression .returning() did that, but it appears to not.


回答1:


Mysql database doesn't support returning statement and it returns just count of updated rows http://dev.mysql.com/doc/refman/5.7/en/update.html.

In your case looks like you must first query ids of the rows to be updated and then update and fetch them inside a transaction.

Like this:

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


来源:https://stackoverflow.com/questions/41598701/how-to-get-a-list-of-all-updated-records-in-knex-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!