关于CodeIgniter中的事务的问题

时间:2013-05-03 04:56:15

标签: php mysql codeigniter transactions

我有2个型号:modelA,modelB。我想在myController的CI事务中实现与这些模型相关的2个操作。 E.x:

$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()失败时它必须回滚。怎么修?非常感谢

1 个答案:

答案 0 :(得分: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();
 }