Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have more than one model functions that are executed before transaction is completed. For example

$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 incase the process of insert or update is interrupted at any point the transaction can be rollback or committed accordingly...

Is there any possibility I can use these below lines 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 a good practice if not what is the best way to handle such transactions?

like image 359
Syed Sajid Avatar asked May 21 '14 11:05

Syed Sajid


1 Answers

Your first alternative is proper.

Transaction logic is at the database level. Codeigniter does not document doing it at the 'table' level ( see http://www.codeigniter.com/user_guide/database/transactions.html).

Your second alternative does not make sense - the transaction encompasses different tables.

like image 172
websterridge Avatar answered Nov 06 '22 05:11

websterridge