How does Zend\Db in ZF2 control transactions?

Greg.Forbes picture Greg.Forbes · Dec 12, 2012 · Viewed 13.1k times · Source

The ZF1 Zend_Db reference manual has an entire section on performing transactions.

The ZF2 Zend\Db reference manual lacks any documentation on transactions.

How do I perform transactions in ZF2? Example code would be helpful.

Answer

Diemuzi picture Diemuzi · Dec 13, 2012

You've got it. The proper way to Begin, Commit, and Rollback Transactions is as follows:

$this->getAdapter()->getDriver()->getConnection()->beginTransaction();

$this->getAdapter()->getDriver()->getConnection()->commit();

$this->getAdapter()->getDriver()->getConnection()->rollback();

Just to put this out there too you can also get the Last ID created by:

$this->getAdapter()->getDriver()->getConnection()->getLastGeneratedValue()

If you are using pgSQL you will need to add the sequence to return the Last ID created:

$this->getAdapter()->getDriver()->getConnection()->getLastGeneratedValue('mail_mailid_seq')