mkk
mkk

Reputation: 7693

doctrine 2.1 - entity cannot be persisted

Doctrine version 2.1

i am persisting a lot of objects, that is why I have to do $this->entityManager->clear() after $this->entityManager->flush(), however it causes a well known error:

Exception: "A new entity was found through the relationship 'Entities\A#B' that was not configured to cascade persist operations for entity: Entities\B@00000000550760cc00000000b0edf71c. Explicitly persist the new entity or configure cascading persist operations on the relationship. If you cannot find out which entity causes the problem implement 'Entities\B#__toString()' to get a clue."

It works for the first flush, but it does not work for all the others. When I comment $this->entityManager->clear();

Here is the code sample:

  if ($flushCounter % 50 == 0) {
    $this->entityManager->flush();
    $this->entityManager->clear();
    //$this->entityManager->detach($B); <- with these two lines commented I tried to fix the error, but it did not work
    //$B = $this->entityManager->find(ENTITY_NAMESPACE . "\B", (int) $B_id);
  }
  $flushCounter++;

I will repeat that commenting out clear() function fixes the issue but i do not want to do that unless there is a better way to manage memory

Upvotes: 1

Views: 1533

Answers (2)

Jens Wegar
Jens Wegar

Reputation: 4872

What helped for me was to clear only the entity that was getting inserted in huge amounts (> 500.000), leaving the rest of the associated objects of that entity in memory

if ($repcount++ % 1000 == 0) {
    $em->flush();   
    $em->clear('Entity\Class\Using\Memory');
}

This though afaik only works with never versions of doctrine (> 2.2.0) and symfony2 (>2.1)

Upvotes: 1

mkk
mkk

Reputation: 7693

What was missing is persist on $B after fetching it again.

 if ($flushCounter % 50 == 0) {
    $this->entityManager->flush();
    $this->entityManager->clear();
    $B = $this->entityManager->find(ENTITY_NAMESPACE . "\B", (int) $B_id);
    $this->entityManager->persist($B);
  }
  $flushCounter++;

Upvotes: 0

Related Questions