We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Transactions and afterDelete

I want to use transactions to avoid data loss on (for example) SQL fails. This works good with:

$this->db->begin();
if($user->delete() == false) {
    $this->db->rollback();
}

.. other SQL statements ..

$this->db->commit();

When one of the queries failed, the record is still in the database, as expected. But there is one problem. The model I want to delete has a relation. The related model has an afterDelete() function that delete files from the server. The files are also deleted when the transaction failed and is rolled back, so the afterDelete function is also called when the transaction failed. How can I avoid this?

Interesting... i was thinking rollback do all needs and didnt go to afterDelete method. I will check and reply. (can u give mi an example what sql fail could be?)



1.0k

I didn't work on this project for some days. It can be hard to test a SQL transaction in a framework I think. So I did a test with a syntax error in one of the queries.

$this->db->begin();
if($user->delete() == false) {
    $this->db->rollback();
}

$robots = $this->db->fetchAll("UPDATE robots SET field = value WHERE id 9");
if(!$robots) {
    $this->db->rollback();
}

$this->db->commit();

The robots query failed and everything is rolled back. So the database is ok, but the afterDelete function is executed. Or is this a bad test?