私は一般的にトランザクションに慣れていませんが、特に 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 でロールバックする必要があります。私のモデルはすべて「犬」データベースにあるので、トランザクションがモデルの機能に影響を与えると思います。たぶん、このようなモデルを使用することはできません。どんな助けでも大歓迎です!ありがとう!