B
B
BonBon Slick2021-09-15 18:06:16
Doctrine ORM
BonBon Slick, 2021-09-15 18:06:16

How to hint to Doctrine / Unit of Work that we are working with existing data after serialization?

We have an entity, we get it from the database

public function find(string $id): ?DomainEntity {
        /** @var DoctrineEntity|null $entity */
        $entity = $this->findOneBy(['id' => $id]);
        if (true === $entity instanceof DoctrineEntity) {
            $entity = $this->coverter->covertDoctrineToDomainEntity($entity);
        }
        return $entity;
    }


The service that uses DomainEntity converts it back to
$entity = $this->coverter->covertDomainEntityToDoctrine($domainEntity);


And this is where the problems begin, because after the first conversion covertDoctrineToDomainEntity
$entityManger->persist(this->coverter->covertDomainEntityToDoctrine($domainEntity);

unit of work loses connection. Converting a doctrine entity to any other object, serializing it, and other similar actions are tantamount to deleting it from the cache, UoW memory
$entityManger->clear(DoctrineEntity::class);
        $entityManger->detach($doctrineEntity);
        $entityManger->remove($doctrineEntity);

under the hood
$this->unitOfWork->remove($entity);

This causes Doctrine 2 to treat the entity as a new entity and insert it as a new entity. Duplicate Entry Exception

So, how to hint to the doctrine, unit of work, that we are dealing with an already existing object?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question