Home » Php » php – kohana transaction with orm

php – kohana transaction with orm

Posted by: admin July 12, 2020 Leave a comment

Questions:

is it possible (how) to use mysql transactions and rollbacks using kohana ORM ?

How to&Answers:

SQL Transactions in Kohana 3.x are not done the same way as in 2.x. In 3.x, the database class comes with transaction methods:

$db->begin();
$db->commit();
$db->rollback();

This also works if you are using ORM stuff. Just initiate the transaction before ORM saves, updates, a or deletes.

Read more in this post:
http://dev.strategystar.net/2011/10/sql-transactions-with-kohana-3-x/

In 2.x, transactions had to be done manually:

$this->db->query("START TRANSACTION")

Answer:

Check out the official forums. It shows an example on how to use transactions with Ko3:

$db->query(NULL, 'TRANSACTION START');  
// Do stuff  
$db->query(NULL, 'COMMIT');

How to do it with version 2, I don’t know. I’m still new to kohana myself, and learning Ko3 rather than 2. But I’m guessing it’s quite similar.

Answer:

I’ve created a Kohana module that makes using transactions a lot easier:

https://github.com/brazzy/kohana-transactional

It does, however, require at least Kohana 3.1. But then you just add

public $_transactional = true;

to the controller, and all actions are automatically executed inside a transaction, which is rolled back when the action fails with an exception.