Yii2.0的事务嵌套

  • Post author:
  • Post category:其他


单个事务

$tr = Yii::$app->db->beginTransaction();
try {
    if($this->delete() == false){
        throw new \Exception(json_encode ($this->getErrors ()));
    }
    $res = $userInfo_model->updateAll(['deleted'=>'1'],['deleted'=>0,'source'=>self::tableName(),'relation_id'=>$this->id]);
    if($res == true){
        throw new \Exception(json_encode ($userInfo_model->getErrors ()));
    }
    $tr->commit ();
    return true;
} catch (\Exception $e) {
    $tr->rollBack ();
    return false;
}

事务嵌套

public function UserInfoDelete()
{
    // 外层事务
    $tr = Yii::$app->db->beginTransaction();
    try {
        if($this->delete() == false){
            throw new \Exception(json_encode ($this->getErrors ()));
        }
        $model = new CustomerForm();
        $model =  $model->findOne('11');
        $res = $model->UserInfoDelete();  // 调用内层事务
        // if($res){
        //     throw new \Exception('内层事务失败'));
        // }
        $userInfo_model = new UserInfoForm();
        $count = $userInfo_model->find()->where(['deleted'=>0,'source'=>self::tableName(),'relation_id'=>$this->id])->count('*');
        if($count > 0){
            $res = $userInfo_model->updateAll(['deleted'=>'1'],['deleted'=>0,'source'=>self::tableName(),'relation_id'=>$this->id]);
            if($res == true){
                throw new \Exception(json_encode ($userInfo_model->getErrors ()));
            }
        }
        $tr->commit ();
    } catch (\Exception $e) {
        $tr->rollBack ();
    }
}
public function UserInfoDelete()
{
    // 内层事务
    $tr = Yii::$app->db->beginTransaction();
    try {
        if($this->delete() == false){
            throw new \Exception(json_encode ($this->getErrors ()));
        }
        $userInfo_model = new UserInfoForm();
        $count = $userInfo_model->find()->where(['deleted'=>0,'source'=>self::tableName(),'relation_id'=>$this->id])->count('*');
        if($count > 0) {
            $res = $userInfo_model->updateAll(['deleted' => '1'], ['source' => self::tableName(), 'relation_id' => $this->id]);
            if ($res == false) {
                throw new \Exception(json_encode($userInfo_model->getErrors()));
            }
        }
        $tr->commit ();
        // return true;
    } catch (\Exception $e) {
        $tr->rollBack ();
        // return false;
    }
}

外层事务里边调用一个方法,这个方法内还有一个事务(内层事务),然后发现内层事务抛出异常后外层事务继续执行,也就是外层事务捕捉不到内层事务抛出的异常。

在内层事务return false/true,外层事务里进行判断,然后决定是否回滚操作(注释的部分),这样外层事务就会收到内层事务的影响。