yii2 数据库事务

来源:互联网 发布:淘宝手机端优惠券设置 编辑:程序博客网 时间:2024/06/08 09:16

//删除profile 和 user 表中的各一条记录,如果未报异常,则提交,如果出现异常,则进行回滚,此次操作无效

try{

            $userid = (int)Yii::$app->request->get('userid');
            if (empty($userid)) {
                throw new \Exception();
            }
            $trans = Yii::$app->db->beginTransaction();//开始事务
            if ($obj = Profile::find()->where('userid = :id', [':id' => $userid])->one()) {
                $res = Profile::deleteAll('userid = :id', [':id' => $userid]);
                if (empty($res)) {
                    throw new \Exception();
                }
            }
            if (!User::deleteAll('userid = :id', [':id' => $userid])) {
                throw new \Exception();
            }
            $trans->commit();
        } catch(\Exception $e) {
            if (Yii::$app->db->getTransaction()) {
                $trans->rollback();//回滚
            }
        }
原创粉丝点击