ThinkPHP5 事务写法

1、事务写法

事务写法要求数据表格式为innoDB,不能是MyISAM

所有涉及到多表同时操作成功,整个操作都成功,才能算成功的,都要用事务写法

所有涉及到用户积分变动的用户操作,都要用事务写法

如:发主题帖、加入版块等用户操作

事务的基本写法

self::beginTrans();
try{
	$thread_id=self::add($thread_data);
	$post_data['tid']=$thread_id;
	$post_id=ComPost::add($post_data);
	self::update(['post_id'=>$post_id],['id'=>$thread_id]);
	if($data['status']==1){//如果不需要审核,则论坛帖子数和最后编辑时间更新
		$forum_data=[
			'last_post_time'=>$data['create_time'],
		];
		ComForum::update($forum_data,['id'=>$data['fid']]);
		ComForum::where('id',$data['fid'])->setInc('post_count');
		ComForum::where('id',$data['fid'])->setInc('thread_count');
		UserModel::where('uid',$data['author_uid'])->setInc('post_count');
	}
	UserTaskNew::newSendThread($data['author_uid']); //发帖新手任务
	UserTaskDay::daySendThread($data['author_uid']); //每日发帖任务
	action_log($data['author_uid'],3,'发布主题帖','com_thread',$thread_id);
	self::commitTrans();
	return $thread_id;
}catch (\Exception $e){
	self::rollbackTrans();
	self::setErrorInfo('发布过程中出现异常!发布失败:'.self::getErrorInfo().$e->getMessage());
	return false;
}

转载于:https://my.oschina.net/zzlzheng/blog/3062151

你可能感兴趣的:(ThinkPHP5 事务写法)