我对一般的交易不熟悉,尤其是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。我的模型都在“狗”数据库中,所以我认为交易会带入模型的功能。也许你不能使用这样的模型。任何帮助将不胜感激!谢谢!
答案 0 :(得分:2)
嗯,我知道这篇文章很古老,但这是我的2美分:
我不这么认为:
if(!$this->descriptions->insert($new_description))
将起作用,导致CI活动记录中的插入功能始终返回TRUE(成功与否)。如果您使用调试模式,CI将在出错时停止并向用户抛出屏幕消息,但插入功能仍将返回TRUE。
所以,如果你愿意用CI“manualy”控制交易,你将不得不使用这样的东西:
...
$this->db->trans_begin();
$this->db->insert('FOO');
if ($this->db->trans_status() === FALSE){
$this->db->trans_rollback();
}else{
$this->db->trans_commit();
}
希望这可以帮助别人...某个时候......某个地方
答案 1 :(得分:1)
也许,这是因为您使用$ dog_db连接,并回滚了不存在的$ booze_db事务?(或者这是一个错字?)