5

In Symfony2, is it possible to check if particular entity was already persisted and is present in the EntityManager?

I'm working with some data import and some of the records might be exact duplicates. I'm doing bulk inserts, i.e., calling flush() only after certain amount of entities were persisted. So, I need to check if the entity I am trying to persist is not in the EntityManager already.

Vitalius
  • 127
  • 3
  • 8
  • As in before flushing? – qooplmao Jul 16 '14 at 09:06
  • I've updated my question. I've tried @paistra suggestion but it didn't work. Also I've found out that another way to check if entity was already persisted is by calling `$this->getDoctrine()->getManager()->contains($entity)` but it returns false, altough the entity was already persisted to EntityManager. – Vitalius Jul 16 '14 at 10:13
  • From your question you don't seem to want to know if an entity has been persisted but if an different entity with duplicate data has been persisted. Is that correct? – qooplmao Jul 16 '14 at 10:22
  • Yes, that's correct. From digging deeper into Doctrine, I see that it generates unique hash for each entity and that's why it returs false. So my guess is I will have to do checking the hard way =) – Vitalius Jul 16 '14 at 10:24
  • I've added an answer as my reply would be cramped. – qooplmao Jul 16 '14 at 10:46

2 Answers2

8

yes you shoud use the unitOfWork http://phpdox.de/demo/Symfony2/classes/Doctrine_ORM_UnitOfWork.xhtml#isEntityScheduled

$uow = $this->getDoctrine()->getManager()->getUnitOfWork()
$exist =  $uow->isEntityScheduled(  $entity );
pietro
  • 902
  • 10
  • 22
  • I haven't formulated the original question clearly enough but your answer does the job in case anyone searches for the answer with the right question in mind. =) – Vitalius Jul 16 '14 at 10:29
0

You could add a serialize method in your object that would create a string of the pertinent data in your model like..

public function serialize()
{
    return serialize(array(
        $this->field1,
        $this->field2,
        .. etc ..
    ));
}

And then before persisting use the scheduled entity insertions to check whether the serialized data has been used before like..

$uow = $this->getDoctrine()->getManager()->getUnitOfWork()
$insertions = $uow->getScheduledEntityInsertions();

$insertions = new ArrayCollection($insertions);

$scheduled = $insertions->filter(
        function(YourModel $model) use ($new) {
            return $model->serialize() === $new->serialize();
        }
    )->first();
// This will either return the relevant model or false
qooplmao
  • 17,622
  • 2
  • 44
  • 69