0

在此处输入图像描述我有以下一段代码,我将一些数据传递给它以生成异常并测试事务回滚是否正在发生。似乎不是,我不确定为什么。有人能帮我吗?谢谢

            $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)

4

2 回答 2

0

默认情况下 pdo 不会抛出异常,只是忽略错误。

$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
于 2013-05-02T15:02:27.517 回答
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);
        }
于 2013-05-02T15:04:10.013 回答