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

Trigger beforeDelete/afterDelete for relationships

Hello,

Is it possible to trigger beforeDelete/afterDelete for relations?

We have this inheritance for example : Client -> hasMany: Products -> hasMany: Images

And we want to delete() the Client and also trigger a beforeDelete() on Images. It doens't seem to work in our tests.



1.8k

if u want just delete rows in DB, make "Foreign key constraint " ON DELETE CASCADE if u want additional logic, just subscribe to beforeDelete (Client model) and do something (for example $this->getImages()->delete() )

We already have ON DELETE CASCADE in mysql. But this does not trigger anything in related models.

I don't know, but I think it certainly possible that Phalcon reads the client table definition and realizes there is a foreign key constraint. Consequently, I don't think it bothers to try to delete images because it knows the database will handle it.

Maybe you can indicate the foreign key when you set up the relationship ( https://docs.phalcon.io/en/latest/reference/models.html#cascade-restrict-actions ) - that might trigger Phalcon to do a little extra work, which might cause the desired events to be triggered.

I've tried with Cascade Action in my model(without ON DELETE CASCADE in mysql), but the problem is it deletes the parent model first. So if I delete a Client, when I get to beforeDelete on Product Images, I no loger know the Client or the Product.

It's a bit hack-ish, but could you put something in the Client::beforeDelete() and Product::beforeDelete() that sets a variable (that holds the necessary IDs) in the appropriate Images objects?