Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Codeigniter one transaction with two model

Is it possible to have one "transaction" with to separate models. I want to insert a post with their tags. Tags and Posts are in two separate models. How can i achive to handle it with a transaction? (Like below:)

$this->db->trans_start();
$this->post_model->insert('...');
$this->tags_model->insert('...');
$this->db->trans_complete();
like image 939
Iamzozo Avatar asked Sep 03 '12 11:09

Iamzozo


1 Answers

As long as you don't have other transaction statements in your model methods, your sample code should work fine.

As per the documentation, you can test it by passing TRUE to $this->db->trans_start():

$this->db->trans_start(TRUE);
// Queries/model calls
$this->db->trans_complete();

if($this->db->trans_status() === FALSE)
{
    // do something if it fails
}

Passing TRUE to trans_start() will automatically rollback the transaction upon completion. You should be able to check auto_increment values on your tables (if applicable) to see if the transaction worked or not.

like image 110
Brendan Avatar answered Oct 07 '22 13:10

Brendan