Doctrine 2: weird behavior while batch processing inserts of entities that reference other entities

爷,独闯天下 提交于 2019-11-29 07:18:46

clear() detaches all entities managed by the entity manager, so $role is detached too, and trying to persist a detached entity creates a new entity.

You should fetch the role again after clear:

$this->em->clear();
$role = $this->em->getRepository('userRole')->find(1);

Or just create a reference instead:

$this->em->clear();
$role = $this->em->getReference('userRole', 1);

As an alternative to arnaud576875's answer you could detach the $user from the entity manager so that it can be GC'd immediately. Like so:

$this->em->flush(); 
$this->em->detach($user); 

Edit:
As pointed out by Geoff this will only detach the latest created user-object. So this method is not recommended.

Another alternative is to merge the role back after the clear:

if (($i % $batchSize) == 0) {
    $this->em->flush();
    $this->em->clear();
    $this->em->merge($role);
}

I'm not sure how expensive merge() is -- if I had to guess, I'd go with arnaud's suggestion of using getReference()

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!