I have the following DB structure and relations:
Posts -> OneToMany,cascade={"persist"} -> Replies -> OneToMany,cascade={"persist"} -> Files entities + files on disk -> event to delete files entities
Posts -> OneToMany,cascade={"persist"} -> Files entities + files on disk -> event to delete files entities
The thing about files is:
What I need is if a post is deleted, it cascades all the way to deleting replies, file entities and its files on disk. The chain of events is:
post->remove();
remove()
{
PostFile::deleteFiles($this);
Reply::deleteFiles($this);
$em->remove($this);
$em->flush();
}
deleteFiles($post)
{
$files = $post->getFiles()->toArray();
foreach ($files as $file) {
$f->delete();
}
}
deleteFiles($post)
{
$replies = $post->getReplies()->toArray();
foreach ($replies as $reply) {
if ($reply) {
ReplyFile::deleteFiles($reply);
}
}
}
deleteFiles($reply)
{
$files = $reply->getFiles()->toArray();
foreach ($files as $file) {
$f->delete();
}
}
Events::addListener('on_file_delete', function($event) {
$f = $event->getFileObject();
$fid = $file->getFileID();
$fpf = PostFile::getByFileID($fid);
$fpf->delete();
$fpmf = ReplyFile::getByFileID($fid);
$fpmf->delete();
});
Everything down the chain works fine, e.g. everything gets deleted, except for the post itself which doesn't get deleted, it has to be deleted twice. Why can that be?
Changing OneToMany,cascade={"persist"} to OneToMany,cascade={"remove"} seemed to have fixed it, now everything gets deleted on first try