2018-07-07 08:44:14 3961次浏览 4条回答 2 悬赏 100 金钱

模型1:Employee 保存员工信息。

模型2:User 保存登录密码等,每一个员工都对应一个user,用uid关联。

下面是我写的代码,感觉不合适,执行的时候,即便失败,id自增字段也会+1。

模型里处理:

public function save($runValidation = true, $attributeNames = null)
{
    if($this->isNewRecord){
        $tr = Yii::$app->db->beginTransaction();  // 创建事务
        try{
            $user = new User();
            $user->username = $this->phone;  //用手机号作为用户名
            $user->email = $this->phone . '@qq.com';  // 邮箱随便填
            $user->setPassword('123456');  // 初始密码
            $user->generateAuthKey();
            if($user->save()){
                $this->uid = $user->id;
                parent::save($runValidation, $attributeNames);
                $tr->commit();  // 提交
            }
        }catch(Exception $exception){
            $tr->rollBack();  // 回滚
            return false;
        }
        return true;
    }else{
        return parent::save($runValidation, $attributeNames); // TODO: Change the autogenerated stub
    }
}
  • 回答于 2018-07-09 08:56 举报

    原理很简单,事务只要不执行到$tr->commit();提交,数据就不会记录。程序运行轨迹一测便知哪问题

  • 回答于 2018-07-09 08:40 举报

    是不是 myisam 表

  • 回答于 2018-07-07 13:02 举报

    自增加1 是默认的.

  • 回答于 2018-07-07 10:29 举报

    要想事务回滚,必须抛出异常。
    $user->save() 加个 else{throw new Exception('错误信息')}

    2 条回复
    回复于 2018-07-07 14:31 回复
    $tr = Yii::$app->db->beginTransaction();  // 开始事务
    try{
        $user = new User();
        $user->username = $model->phone;
        $user->email = $model->phone . '@qq.com';
        $user->setPassword('123456');
        $user->generateAuthKey();
        if($user->save()){
            $model->uid = $user->id;
            if(!$model->save()){
                $error = array_values($model->getFirstErrors())[0];
                throw new Exception($error);//抛出异常
            }
        }else{
            $error = array_values($user->getFirstErrors())[0];
            throw new Exception($error);//抛出异常
        }
        $tr->commit();  // 提交记录(执行事务)
        return $this->redirect(['view', 'id' => $model->id]);
    }catch(Exception $exception){
        $tr->rollBack();  // 记录回滚(事务回滚)
        return $this->render('create', ['model' => $model]);
    }
    

    如上代码,如果$user->save()保存失败的话,会直接catch,不会走else语句

    回复于 2018-07-15 10:45 回复

    如果事务没有else 那就找到最近的保存 肯定有错误,你只要挨个die截取看看 就知道哪有问题了

    觉得很赞
您需要登录后才可以回答。登录 | 立即注册
墨轩娣
董事长

墨轩娣 无锡

注册时间:2015-03-25
最后登录:2小时前
在线时长:265小时32分
  • 粉丝38
  • 金钱55135
  • 威望150
  • 积分59285

热门问题