Doctrine - A new entity was found through the relationship Doctrine - A new entity was found through the relationship symfony symfony

Doctrine - A new entity was found through the relationship


I had the same problem and it was the same EntityManager. I wanted to insert an object related ManyToOne. And I don't want a cascade persist.

Example :

$category = $em->find("Category", 10);$product = new Product();$product->setCategory($category)$em->persist($product);$em->flush();

This throws the same exception for me.

So the solution is :

$category = $em->find("Category", 10);$product = new Product();$product->setCategory($category)$em->merge($product);$em->flush();


In my case a too early call of

$this->entityManager->clear();

caused the problem. It also disappeared by only doing a clear on the recent object, like

$this->entityManager->clear($capture);


My answer is relevant for topic, but not very relevant for your particular case, so for those googling I post this, as the answers above did not help me.

In my case, I had the same error with batch-processing entities that had a relation and that relation was set to the very same entity.

WHAT I DID WRONG:

When I did $this->entityManager->clear(); while processing batch of entities I would get this error, because next batch of entities would point to the detached related entity.

WHAT WENT WRONG:

  1. I did not know that $this->entityManager->clear(); works the same as $this->entityManager->detach($entity); only detaches ALL of the repositorie`s entities.

  2. I thought that $this->entityManager->clear(); also detaches related entities.

WHAT I SHOULD HAVE DONE:

I should have iterated over entities and detach them one by one - that would not detach the related entity that the future entities pointed to.

I hope this helps someone.