CodeIgniter Forums

Full Version: models and db transactions
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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?
Just search documentation for "transactions" and enjoy reading this chapter:
(03-11-2020, 02:29 PM)zahhar Wrote: [ -> ]Just search documentation for "transactions" and enjoy reading this chapter:

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'

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.
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:

//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(); }