如何将两个更新请求合并为一个?

How can i combine two update requests into one?

我现在有一个有效的代码。

await Users.update({ selected: false }, { where: { userId: req.body.userId } });
await Users.update(
  {
    selected: req.body.selected,
    descr: req.body.note
  },
  {
    where:
    {
      entId: req.body.id,
      userId: req.body.userId
    }
  }
);

但是如果可以将这两个查询合二为一呢?我需要传递的 'selected' 和 'note' 字段在 table 中有条件地更改。并且 table 中用户固有的所有其他 'selected' 字段变为错误。 不幸的是,我没有在文档中找到类似的东西。预先感谢您的帮助!

不幸的是,在 Sequelize 中没有像 bulkUpdate 这样的方法,因此您需要调用 update 两次,最好使用事务将这两个查询作为一个原子操作。

await Sequelize.transaction(async transaction => {
  await Users.update({ selected: false }, { where: { userId: req.body.userId }, transaction });
  await Users.update(
    {
      selected: req.body.selected,
      descr: req.body.note
    },
    {
      where:
      {
        entId: req.body.id,
        userId: req.body.userId
      },
      transaction
    }
  );
});

您可以使用续集 transaction 并将其包裹在 try/catch,

// define transaction outside the try/catch so you can rollback if needed
const transaction = await sequelize.transaction();

try {

await Users.update({ selected: false }, { where: { userId: req.body.userId }, transaction })
    .then((r) => r)
    .catch((e) => {
        throw e;
    });

await Users.update(
    {
        selected: req.body.selected,
        descr: req.body.note
    },
    {
        where: {
            entId: req.body.id,
            userId: req.body.userId
        },
        transaction
    }
    )
    .then((r) => r)
    .catch((e) => {
        throw e;
    });

  // always call commit at the end
  await transaction.commit();
  return true;

 } catch (error) {
   // always rollback
   await transaction.rollback();
   console.log(error);
   throw error;
 }