我有以下代码片段,我传递了一些数据来生成异常并测试是否发生了事务回滚。它似乎不是,我不知道为什么。 有人能帮我吗?感谢
$transaction = Yii::app()->db->beginTransaction();
try {
//.....
//call private methods
$category = MyController::saveCategory($params);
$test_saved = MyController::saveTest($params);
MyController::saveCommunity($param); // here is an exception and it should rollback the transaction but it doesn't
$transaction->commit();
} catch(Exception $e) {
$transaction->rollback();
throw new Exception($e);
}
private function saveCommunity($param){
$community = new Community();
$community->user_id = $user_id;
$community->name = $name;
$community->id = 71; // this is a duplicate primary key and will generate an exception
try{
$community->save(false, null);
}catch(Exception $e){
throw $e;
}
return $community;
}
(mysql表设置为innodb)
答案 0 :(得分:0)
默认情况下,pdo不会抛出异常,只会忽略错误。
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
答案 1 :(得分:0)
尝试更改负责异常抛出的代码:
try{
$community->save(false, null);
}catch(Exception $e){
throw $e;
}
类似于:
if(!$community->save(false, null))
throw new Exception('Error saving');
并删除此处抛出的异常:
} catch(Exception $e) {
$transaction->rollback();
//throw new Exception($e);
}