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

24,603

Solution 1

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.

Solution 2

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

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

I'd prefer to have them both in the same function in the model as the delete can be called from a couple of controllers.

Share:
24,603
Syed Sajid
Author by

Syed Sajid

Updated on June 25, 2020

Comments

  • Syed Sajid
    Syed Sajid almost 4 years

    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?