W3Cschool
恭喜您成為首批注冊(cè)用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
模型中提供了對(duì)事務(wù)操作的支持,但前提需要數(shù)據(jù)庫支持事務(wù)。
Mysql
中的 InnoDB
和 BDB
存儲(chǔ)引擎支持事務(wù),如果在 Mysql 下使用事務(wù)的話,需要將數(shù)據(jù)庫的存儲(chǔ)引擎設(shè)置為 InnoDB 或 BDB。
SQLite
直接支持事務(wù)。
模型中提供了 startTrans
,commit
和 rollback
3 種方法來操作事務(wù)。
startTrans
開啟事務(wù)commit
正常操作后,提交事務(wù)rollback
操作異常后進(jìn)行回滾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();
}
}
}
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();
});
}
})
使用事務(wù)時(shí),要一直使用 startTrans
,commit
和 rollback
這 3 個(gè)方法進(jìn)行操作,使用起來有一些不便。為了簡(jiǎn)化這一操作,模型中提供了 transaction
方法來更加方便的處理事務(wù)。
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 () => {}
。
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ù)中處理真正的邏輯,并需要返回。
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: