2013-05-03 48 views
0

我有2個模型:modelA,modelB。我想在myController的CI事務中實現與這些模型相關的2個操作。例如:關於CodeIgniter中事務的問題

$this->db->trans_start(); 

$this->modelA->uodateA(conditions, item); 
$this->modelB->updateB(conditions, item); 
// with conditions and item is valid 
$this->db->trans_complete(); 

if ($this->db->trans_status() === FALSE) 
{ 
//handle when failed 
} 

這裏是這些模式2操作:)

public function updateA($where = array(), $item = array(), $auth = NULL){ 
     if(!is_array($item) && empty($item)) return FALSE; 

     if(is_numeric($where)){ 
      $where = array('vote_id'=>$where); 
     } 
     $this->db->where($where)->update($this->_table,$item); 


     return ($this->db->affected_rows() > 0); 
    } 


public function updateB($where = array(), $item = array(), $auth = NULL){ 
     if(!is_array($item) && empty($item)) return FALSE; 

      if(is_numeric($where)){ 
       $where = array('vote_id'=>$where); 
      } 

     $this->db->where($where)->update($this->_table,$item); 
     return ($this->db->affected_rows() > 0); 
    } 

雖然updateB(失敗(例如:不能有要更新的記錄,用字符串值更新的int字段... )但trans_status()仍然返回true。我想當updateB()失敗時它必須回滾。怎麼修?非常感謝

+0

你可以發佈你的模型代碼嗎? – 2013-05-03 05:03:58

+0

@Kishor:我更新了 – secretlm 2013-05-03 07:38:44

+0

只要您的模型方法中沒有其他交易語句,您的示例代碼應該可以正常工作。 – 2013-05-03 09:43:01

回答

0

你可以試試這個

$this->db->trans_begin(); 

$this->modelA->insertA(); 
$this->modelB->updateB(); 

if ($this->db->trans_status() === FALSE) 
{ 
    $this->db->trans_rollback(); 
} 
else 
{ 
    $this->db->trans_commit(); 
} 
+0

我嘗試過,但仍然失敗。 – secretlm 2013-05-03 06:29:55

+0

你應該在一個模型中寫上面的代碼。你可以發佈你的兩個查詢嗎?它會幫助我們糾正。 – Sudz 2013-05-03 06:45:50

+0

我更新了我的代碼 – secretlm 2013-05-03 07:56:38