• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
models and db transactions

#1
Is it possible for a model to use database transactions?

I want to be able to roll back on insert/update errors as well as use the "Test Mode" for development. Is there any way to do this?
Reply

#2
Just search documentation for "transactions" and enjoy reading this chapter: https://codeigniter4.github.io/userguide...ransaction
Reply

#3
(03-11-2020, 02:29 PM)zahhar Wrote: Just search documentation for "transactions" and enjoy reading this chapter: https://codeigniter4.github.io/userguide...ransaction

Sorry if I misunderstood something. Can I call an insert from my model from within the start/end? I want to still use the built in insert/update etc. functions from the model.

As an approximate example:
PHP Code:
$myModel = new MyModel;

$myDataHere = [
   
'field1' => 'data',
   
'field2' => 'data'
]

$this->db->transStart();
$myModel->insert($myDataHere);
$this->db->transComplete(); 
Will this work?

Or is there a way I can have the same effect but with the transaction start and end automatically called? So I don't need to specify every time.
Reply

#4
Your example makes little sent. By default all databases autocommitting transactions. So they are doing exactly what you showed: they start transation, execute your query, and upon success immidiately commit and close transaction. So yoiu do not need to explicitly utilize them every time.

When you do need transaction is to ensure that several queries (affecting one or more tables in DB) are either succesfully executed all together, or not executed at all, to prevent partial execution.


See this example: you are building a marketplace that processes payments and earns some commission from each payment. When user purchases goods, you should do a lot of stuff: reserve items in stock, get confirmation that user paid the bill from payment gateway, pay taxes, etc. Imagine that if user does not pay  

PHP Code:
$this->db->transBegin();

//Step 1: reserve stock
//Some business logic here that might throw exceptions
$this->db->query("UPDATE stock...");

//Step 2: settle money
//Here we might wait till payment processor confirms payment
$this->db->query("INSERT INTO payments...");
$this->db->query("INSERT INTO taxes...");
$this->db->query("INSERT INTO commissions...");

//Step 3: Create invoice
//Again some business logic that might go wrong
$this->db->query("INSERT INTO invoices...");

if (
$this->db->transStatus() AND OTHER RELEVANT CHECKS) { $this->db->transCommit(); } else { $this->db->transRollback(); } 
Reply


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2020 MyBB Group.