Given:
Two custom classes in Magento with a Many-to-One relationship between them.
The child holds a foreign key to the parent.
The database is set to cascade deletes.
There are cases when a child’s reference changes to a different parent. In some of those cases, I want to delete the parent in the afterSave method of the child. When I do this, the child itself disappears, since the change of FK to the new parent hasn’t been written to the database yet, and the database level cascade kicks in.
How can I arrange for the deletion of the parent object after the write of the new foreign key in the child object?
afterSavetriggers before the query has been written to DB, as you’ve noticed yourself. You need to use*_save_commit_afterevent. Where asterisk is your Modelsevent_prefix. Create an Observer and listen for this event, that way you can be sure that info in DB has been already updated, and you won’t suffer the foreign key effect.