2013-05-02 145 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);