【问题标题】:Atomic operations in SequelizeSequelize 中的原子操作
【发布时间】:2014-12-03 14:42:06
【问题描述】:

我是 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()
})

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

【问题讨论】:

    标签: sql node.js orm sequelize.js


    【解决方案1】:

    简而言之,使用事务:

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

    在最新版本(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 })
        ]);
    });
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-13
      • 2010-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-25
      • 1970-01-01
      相关资源
      最近更新 更多