2013-05-02 223 views
0

enter image description here我有以下的一段代码,我把它传递给一些数据来产生一个异常,并测试事务回滚是否发生。它似乎不是,我不知道为什么。 有人可以帮助我吗?感谢Yii交易没有回滚

  $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

我使用mysql我发现mysql autocommit crea te和drop table,所以PDO可以回滚了,交易 – 2013-05-02 16:23:36

回答

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); 
     } 
+0

仍然不起作用。我试过这[一](http://www.yiiframework.com/forum/index.php/topic/6659-cdbtransaction-is-inactive-and-cannot-perform-commit-or-roll-back-operations/)也一样 – 2013-05-02 15:10:27

0

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

$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);