0

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

4

2 回答 2

2

好吧,我知道这篇文章很古老,但这是我的 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();

}

希望这可以帮助某人……有时……某处

于 2012-04-30T18:16:08.567 回答
1

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

于 2010-04-20T18:19:57.363 回答