2010-04-20 52 views
0

我是一般的交易新手,但特別是與CodeIgniter。我使用的是InnoDB和一切,但是當我希望他們交易時,我的交易不會回滾。這是我的代碼(稍微簡化)。在codeigniter與多個表的交易

  $dog_db = $this->load->database('dog', true); 
      $dog_db->trans_begin(); 

      $dog_id = $this->dogs->insert($new_dog); //Gets primary key of insert 
      if(!$dog_id) 
      { 
       $dog_db->trans_rollback(); 
       throw new Exception('We have had an error trying to add this dog. Please go back and try again.'); 
      } 

      $new_review['dog_id'] = $dog_id; 
      $new_review['user_id'] = $user_id; 
      $new_review['date_added'] = time(); 

      if(!$this->reviews->insert($new_review)) //If the insert fails 
      { 
       $dog_db->trans_rollback(); 
       throw new Exception('We have had an error trying to add this dog. Please go back and try again.'); 
      } 

       //ADD DESCRIPTION 
      $new_description['description'] = $add_dog['description']; 
      $new_description['dog_id'] = $dog_id; 
      $new_description['user_id'] = $user_id; 
      $new_description['date_added'] = time(); 

      if(!$this->descriptions->insert($new_description)) 
      { 
       $dog_db->trans_rollback(); 
       throw new Exception('We have had an error trying to add this dog. Please go back and try again.'); 
      } 

       $dog_db->trans_rollback(); //THIS IS JUST TO SEE IF IT WORKS 
       throw new Exception('We have had an error trying to add this dog. Please go back and try again.'); 

      $dog_db->trans_commit(); 
} 

catch(Exception $e) 
{ 
    echo $e->getMessage(); 
} 

我沒有收到任何錯誤消息,但也沒有回滾。它應該在提交之前在最終的trans_rollback處回滾。我的模型都是在「狗」數據庫上,所以我認爲交易將進入模型的功能。也許你不能使用這樣的模型。任何幫助將不勝感激!謝謝!

回答

1

也許,那是因爲你連接使用$ dog_db以及回退不存在的$ booze_db交易

+0

是的,這是一個錯字,哈哈。編輯。 – Ethan 2010-04-21 01:04:48

2

嗯,我知道這個帖子是古董,但這裏是我的2分錢?(或者它是一個錯字?):

我不認爲這樣的:

if(!$this->descriptions->insert($new_description)) 

會的工作,導致從CI活動記錄插入函數總是返回TRUE(成功與否)。如果您使用的是調試模式,則CI將在出錯時停止並向用戶發出屏幕消息,但插入功能仍然會返回TRUE。

所以,如果你願意控制交易「manualy」與CI,你將不得不使用這樣的事情:

... 

$this->db->trans_begin(); 

$this->db->insert('FOO'); 

if ($this->db->trans_status() === FALSE){ 

    $this->db->trans_rollback(); 

}else{ 

    $this->db->trans_commit(); 

} 

希望這可以幫助別人......有時....某處