Sequelize 中的原子操作

k88*_*074 2 sql orm node.js sequelize.js

我是 Sequelize 的新手,所以我有一个非常简单,也许微不足道的问题。考虑文档中的示例:

var project = Project.build({
  title: 'my awesome project',
  description: 'woot woot. this will make me a rich man'
})

var task = Task.build({
  title: 'specify the project idea',
  description: 'bla',
  deadline: new Date()
})
Run Code Online (Sandbox Code Playgroud)

我想确保我要么保存它们要么都不保存。我怎么做?换句话说,我如何原子地对多个表执行创建/更新操作?

Jan*_*ier 5

简而言之,使用事务:

sequelize.transaction().then(function (t) {
    return sequelize.Promise.all([
      Project.create({
        title: 'my awesome project',
        description: 'woot woot. this will make me a rich man'
      }, { transaction: t }), 
      Task.build({
        title: 'specify the project idea',
        description: 'bla',
        deadline: new Date()
      }, { transaction: t })
    ]).then(function onFulfilled (project, task) {
        return t.commit();
    }, function onRejected(err) {
        return t.rollback();
    });
});
Run Code Online (Sandbox Code Playgroud)

在最新版本 (2.0-rc2) 中,这也可以更简洁地写成:

sequelize.transaction(function (t) {
    return sequelize.Promise.all([
      Project.create({
        title: 'my awesome project',
        description: 'woot woot. this will make me a rich man'
      }, { transaction: t }), 
      Task.build({
        title: 'specify the project idea',
        description: 'bla',
        deadline: new Date()
      }, { transaction: t })
    ]);
});
Run Code Online (Sandbox Code Playgroud)

通过将回调传递给transaction而不是调用then。回调返回一个promsie链,事务被提交或回滚,取决于返回的promise是否成功。这意味着如果任何操作Promise.all失败,事务将被回滚。