问题
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?
回答1:
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");
回答2:
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);
来源:https://stackoverflow.com/questions/13789965/transaction-doesnt-work-in-yii