【问题标题】:Transactions in codeigniter with multiple tables具有多个表的 codeigniter 中的事务
【发布时间】:2010-04-20 01:06:35
【问题描述】:

我是一般事务的新手,尤其是 CodeIgniter。我正在使用 InnoDB 和所有东西,但是当我想要它们时,我的事务并没有回滚。这是我的代码(略微简化)。

            $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。我的模型都在“狗”数据库上,所以我认为交易会带入模型的功能中。也许你不能使用这样的模型。任何帮助将不胜感激!谢谢!

【问题讨论】:

    标签: mysql codeigniter transactions rollback


    【解决方案1】:

    好吧,我知道这篇文章很老套,但这是我的 2 美分:

    我不这么认为:

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

    会起作用,因为 CI 活动记录中的插入函数总是返回 TRUE(成功与否)。如果您使用调试模式,CI 将在出错时停止并向用户抛出屏幕消息,但插入函数仍将返回 TRUE。

    因此,如果您愿意使用 CI“手动”控制事务,则必须使用以下内容:

    ...
    
    $this->db->trans_begin();
    
    $this->db->insert('FOO');
    
    if ($this->db->trans_status() === FALSE){
    
        $this->db->trans_rollback();
    
    }else{
    
        $this->db->trans_commit();
    
    }
    

    希望这对某人有所帮助……有时……某处

    【讨论】:

      【解决方案2】:

      也许是因为您使用 $dog_db 连接,并回滚不存在的 $booze_db 事务?(或者是错字?)

      【讨论】:

      • 是的,这是一个错字,哈哈。已编辑。
      猜你喜欢
      • 2017-11-24
      • 2023-03-16
      • 2018-05-19
      • 2016-08-06
      • 2014-04-29
      • 1970-01-01
      • 2016-05-11
      • 2012-05-13
      • 1970-01-01
      相关资源
      最近更新 更多