Welcome Guest, Not a member yet? Register   Sign In
Codeigniter Transactions
#1

[eluser]Otemu[/eluser]
Hi,

In the user guide you can use transactions like this:

Code:
$this->db->trans_start();
$this->db->query('AN SQL QUERY...');
$this->db->query('ANOTHER QUERY...');
$this->db->query('AND YET ANOTHER QUERY...');
$this->db->trans_complete();

I just wondered if anyone knew if it was possible to use multiple model functions with one transaction action like this:

Code:
function model1(){
$this->db->trans_start();
$this->db->query('AN SQL QUERY...');
}
function model2(){
$this->db->query('ANOTHER QUERY...');
}
}function model3(){
$this->db->query('ANOTHER QUERY...');
}
function model4(){
$this->db->query('AND YET ANOTHER QUERY...');
$this->db->trans_complete();
}

This is just so that I could have some logic on my controller such as depending on results from model1 either run model 2 or model 3 function and then complete with model 4
#2

[eluser]Aken[/eluser]
Try it on some test data and find out. There's no difference to how the queries are run, just because they're called from different PHP files, so it should work fine. (But I don't use them, so I don't know 100%, so you should try it and see.)
#3

[eluser]Otemu[/eluser]
Thanks for the response Aken, I was going to try over the weekend, just thought I ask to see if anyone knew.
#4

[eluser]Unknown[/eluser]
Hi Otemu,

I don't know if you managed to do what you wanted, but here is my solution:

Code:
$this->db->trans_start();

if ($this->model1->action() === FALSE)
    $this->db->_trans_status = FALSE;

if ($this->model2->action() === FALSE)
    $this->db->_trans_status = FALSE;

if ($this->model3->action() === FALSE)
    $this->db->_trans_status = FALSE;

if ($this->model4->action() === FALSE)
    $this->db->_trans_status = FALSE;

$this->db->trans_complete();

#5

[eluser]jonez[/eluser]
[quote author="Aken" date="1359682469"]Try it on some test data and find out. There's no difference to how the queries are run, just because they're called from different PHP files, so it should work fine. (But I don't use them, so I don't know 100%, so you should try it and see.)[/quote]
You are correct, any commands executed between trans_start and trans_complete (that are using that database connection) are part of the transaction even if they are in other models etc.
#6

[eluser]ivantcholakov[/eluser]
@Otemu

I think, your idea would work. But it is not good to build an API where you have to call methods in a specific sequence. At least wrap this sequence within a special method.




Theme © iAndrew 2016 - Forum software by © MyBB