6

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(); 
1
  • where is the problem in your code ? Commented Sep 3, 2012 at 11:52

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

4 Comments

I guess there will be one controller in this case, right? this code will be placed inside the controller???
@Lykos It doesn't have to be. This could be in your model method as well (that is where it should be, realistically). If you are working with DB directly in controller, then yes it is placed in the controller around your DB code.
Personaly I always put my crud in my models, but as Tschempe asked above, is it ok to do $this->db->trans_start(); $this->post_model->insert('...'); $this->tags_model->insert('...'); inside the controller, in order to insert data in to different db tables at once?
@Lykos Yes. Just make sure your model methods don't do any transaction functions and you'll be fine.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.