Transaction doesn't work in Yii

2019-06-05 02:55发布

this is my code:

$transaction = Yii::app()->db->beginTransaction();
            try {
                $tModel->save();
                $activationLink = new ActivationLink;
                $activationLink->User_id = $tModel->id;
                $activationLink->hash1   = User::generateHashCode(100);
                $activationLink->hash2   = User::generateHashCode();
                $activationLink->hash3   = User::generateHashCode();
                $activationLink->time    = time();
                $activationLink->save();                    
                User::sendActivatonLink($tModel->mail,$activationLink->id, $activationLink->hash1, $activationLink->hash2, $activationLink->hash3);
                $transaction->commit();
                $this->redirect(array('view', 'id' => $tModel->id));
            } catch (Exception $e) {
                $transaction->rollback();
                Yii::app()->user->setFlash('error', "{$e->getMessage()}");
                $this->refresh();
            }

$tModel saved but $activationLink doesn't so it should rolled back. but it didn't ,why?

2条回答
劳资没心,怎么记你
2楼-- · 2019-06-05 03:04

Yii save() does not throw an exception, when just the validation fails. Thus you have to check the result of save() yourself:

if (!$model->save())
   $transaction->rollback();

//or:

if (!$model->save())
   throw new Exception("This will trigger my catch statement block");
查看更多
混吃等死
3楼-- · 2019-06-05 03:11

Please check your mysql engine I think you are not using innodb. To execute transaction we must use innodb. Let me know your table type/engine.

OR You also need to add in your code to understand error in log.

throw new Exception($e);

查看更多
登录 后发表回答