直接进入正题,请看下面代码
Db::startTrans();
try {
foreach ($arr as $value) {
Db::startTrans();
try {
if ($value['id'] < 6) {
Db::name('jq_policy_template_log')
->where('id', $value['id'])
->update(['createtime'=>$value['createtime']]);
} else {
throw new \Exception('二级异常');
}
Db::commit();
} catch (\Exception $ee) {
Db::rollback();
echo '二级异常:'.$ee->getMessage();
throw new \Exception('一级异常:'.$ee->getMessage());
}
}
Db::commit();
} catch (\Exception $e) {
Db::rollback();
echo '父级事务出现异常:'.$e->getMessage();
}
echo '---测试结束---';die;
执行结果是:即使4和5commit了,但是整体是什么都没改变
结论:最外层的事务回滚了,那里层的commit是不生效的,通过tp5的源代码不难发现,只有当$this->transTimes为1的时候,才会真正的提交
以上代码稍微改动一下,
将
echo '二级异常:'.$ee->getMessage();
throw new \Exception('一级异常:'.$ee->getMessage());
改为:
echo '二级异常:'.$ee->getMessage();
执行结果为:4和5都生效了,6抛出了二级异常
最终结论:通过对比不难发现,只有最外层的commit时,才会真正的commit提交,因为那时的
t
h
i
s
−
>
t
r
a
n
s
T
i
m
e
s
为
1
,
同
理
可
得
,
只
有
this->transTimes为1,同理可得,只有
this−>transTimes为1,同理可得,只有this->transTimes为1的时候,才会真正的rollback回滚,其他情况都是在做$this->transTimes的“减一”操作。