Javascript 如何将两个更新请求合并为一个?
我现在有了一个有效的代码Javascript 如何将两个更新请求合并为一个?,javascript,orm,sequelize.js,nodes,Javascript,Orm,Sequelize.js,Nodes,我现在有了一个有效的代码 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
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”字段,以便在表中有条件地进行更改。表中用户固有的所有其他“选定”字段都变为false。
不幸的是,我在文档中没有找到类似的内容。提前感谢您的帮助 不幸的是,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
}
);
});
您可以使用sequelize
事务
并将其包装在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;
}