Search code examples
phpmysqlsymfonydoctrine-ormpersist

Doctrine Remove Issue in Symfony2


When I am trying to remove an entity using doctrine it runs a new INSERT statement for the deleted entity.

The setup is like below:

Table 1: file Table 2: gallery Table 3: gallery_media

File is a standalone table that tracks uploaded file details. Gallery is also a standalone table that stores information of galleries. gallery_media is a gerund (many-to-many) table associating files with galleries.

Assume that table 1 & 2 has id fields and table 3 has fileId and galleryId fields.

My Doctrine Code is this (I am using Symfony2):

$this->em->remove($filentity);
$this->em->flush();

Now when I run the code; file entity will be removed and the remove opration will be cascaded meaning that associated gallery_media entries are also deleted. But then suddenly the removed entity reappears in database.

My MySQL log show the below queries are run in given order:

START TRANSACTION
DELETE FROM file WHERE id = '126'
commit
START TRANSACTION
INSERT INTO file (name) VALUES ('someFileName')
UPDATE gallery SET date_updated = '2014-06-10 09:53:38', count_media = 11 WHERE id = 14

My complete code is:

$this->em->remove($filentity);
$this->em->flush();
$newCount= $galleryEntity->getCountMedia() - 1;
$galleryEntity->setCountMedia($newCount);
$this->em->persist(galleryEntity);
$this->em->flush();

I believe that shomehow the entity is not detached after removal. But I am not sure. Maybe entity manager instance is mixed up...

Did anyone encountered a similar issue? If so I'll appreciate some feedback.

Thanks.


Solution

  • My guess is, that $galleryEntity contains the previously deleted file object. When calling persist, the entity manager sees, that file is not yet persisted (because it was deleted previously) and inserts it. Try looking for $fileEntity in your $galleryEntity and manually remove it or $em->refresh($galleryEntity) or retrieve the $galleryEntity from the entity manager after your file was deleted to make sure it isn't "dirty".