Codeigniter: Can I use $ this-> db-> trans_start () and trans_complete in my controller function?

I have several model functions that are executed before the transaction is completed. for instance

$this->model_A->insert('....'); $this->model_C->insert('....'); $this->model_D->insert('....'); $this->model_E->update('....'); 

What is the best way to use trans_start () and trans_complete (), so the insert or update process is interrupted at any time when the transaction can be rolled back or executed accordingly ...

Is it possible to use these lines below in my controller? Like this?

 $this->db->trans_start(); $this->model_A->insert('....'); $this->model_C->insert('....'); $this->model_D->insert('....'); $this->model_E->update('....'); $this->db->trans_complete(); OR $this->model_A->trans_start(); $this->model_A->insert('....'); $this->model_C->insert('....'); $this->model_D->insert('....'); $this->model_E->update('....'); $this->model_A->trans_complete(); 

Is it good practice, if not the best way to handle such transactions?

+6
source share
2 answers

Your first alternative is correct.

Transaction logic is at the database level. Codeigniter does not document this at the β€œtable” level (see http://www.codeigniter.com/user_guide/database/transactions.html ).

The second option does not make sense - the transaction covers different tables.

+7
source

I mentioned the best approach / will work from within the model. In my case, I delete something and then run some SQL to recalculate the totals that are stored in another table. So is something like the following in the model a good approach?

 $this->db->trans_start(); $this->db->delete('table_name', $data); $this->another_model->recalculate_update_thing('....'); $this->db->trans_complete(); 

I would prefer that both of them be in the same function in the model, since deletion can be called from a pair of controllers.

+1
source

Source: https://habr.com/ru/post/969636/


All Articles