models and db transactions |
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: https://codeigniter4.github.io/userguide...ransaction
(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; 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: $this->db->transBegin(); |
Welcome Guest, Not a member yet? Register Sign In |