【问题标题】:Issue about transaction in CodeIgniterCodeIgniter 中关于事务的问题
【发布时间】:2013-05-03 04:56:14
【问题描述】:

我有 2 个模型:modelA、modelB。我想在 myController 的 CI 事务中实现 2 个与这些模型相关的操作。例如:

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

【问题讨论】:

  • 您也可以发布您的型号代码吗?
  • 只要您的模型方法中没有其他事务语句,您的示例代码应该可以正常工作。

标签: php mysql codeigniter transactions


【解决方案1】:

你可以试试这个

 $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();
 }

【讨论】:

  • 您应该在单个模型中编写上述代码。你能发布你的两个查询吗?它将帮助我们纠正。
  • 我认为您的任何查询都不会执行,因为您没有传递任何参数,根据您的逻辑,您编写的函数将始终返回 false 。此外,如果您将变量 $where 声明为数组,那么为什么需要检查 if(is_numeric($where)){....
猜你喜欢
  • 1970-01-01
  • 2011-02-14
  • 1970-01-01
  • 2020-08-29
  • 1970-01-01
  • 2021-04-21
  • 2011-05-24
  • 2011-09-23
  • 1970-01-01
相关资源
最近更新 更多