ThinkJS 事務(wù)

2021-09-17 14:34 更新

事務(wù)

模型中提供了對(duì)事務(wù)操作的支持,但前提需要數(shù)據(jù)庫支持事務(wù)。

Mysql 中的 InnoDB 和 BDB 存儲(chǔ)引擎支持事務(wù),如果在 Mysql 下使用事務(wù)的話,需要將數(shù)據(jù)庫的存儲(chǔ)引擎設(shè)置為 InnoDB 或 BDB。

SQLite 直接支持事務(wù)。

使用事務(wù)

模型中提供了 startTranscommit 和 rollback 3 種方法來操作事務(wù)。

  • startTrans 開啟事務(wù)
  • commit 正常操作后,提交事務(wù)
  • rollback 操作異常后進(jìn)行回滾

ES6 方式

export default class extends think.controller.base {
  * indexAction(){
    let model = this.model("user");
    try{
      yield model.startTrans();
      let userId = yield model.add({name: "xxx"});
      let insertId = yield this.model("user_group").add({user_id: userId, group_id: 1000});
      yield model.commit();
    }catch(e){
      yield model.rollback();
    }
  }
}

動(dòng)態(tài)創(chuàng)建類的方式

module.exports = think.controller({
  indexAction: function(self){
    var model = this.model("user");
    return model.startTrans().then(function(){
      return model.add({name: "xxx"});
    }).then(function(userId){
      return self.model("user_group").add({user_id: userId, group_id: 1000})
    }).then(function(){
      return self.commit();
    }).catch(function(err){
      return self.rollback();
    });
  }
})

transaction 方法

使用事務(wù)時(shí),要一直使用 startTrans,commit 和 rollback 這 3 個(gè)方法進(jìn)行操作,使用起來有一些不便。為了簡(jiǎn)化這一操作,模型中提供了 transaction 方法來更加方便的處理事務(wù)。

ES6 方式

export default class extends think.controller.base {
  * indexAction(self){
    let model = this.model("user");
    let insertId = yield model.transaction( function * (){
      let userId = yield model.add({name: "xxx"});
      return yield self.model("user_group").add({user_id: userId, group_id: 1000});
    })
  }
}

注:Arrow Function 無法和 */yield 一起寫,所以上面為 function *。如果想使用 Arrow Function,可以使用 async,如: async () => {}。

使用動(dòng)態(tài)創(chuàng)建類的方式

module.exports = think.controller({
  indexAction: function(self){
    var model = this.model("user");
    return model.transaction(function(){
      return model.add({name: "xxx"}).then(function(userId){
        return self.model("user_group").add({user_id: userId, group_id: 1000});
      });
    }).then(function(insertId){

    }).catch(function(err){

    })
  }
})

transaction 接收一個(gè)回調(diào)函數(shù),這個(gè)回調(diào)函數(shù)中處理真正的邏輯,并需要返回。

以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)