Doctrine EntityManager clear method in nested entities

百般思念 提交于 2019-12-04 10:06:47

Soon You will hit memory limit. The idea of flush() in batches is ok, but You need to clear() EntityManager at the end of each batch to release used memory.

But in Your case, You will have ORMInvalidArgumentException (a.k.a. "new entity foung through relationship") if You will call $child->setParent($parent); after You did $entityManager->clear();.

Problem is that $parent is now in detached state in UnitOfWork. So You need to put it again in managed state. This can be done by using $entityManager->merge(); or simply by using $parentRepository->find($parent->getId());.

Just make sure to bring up all Entities to managed state after each clear() in case You going to use them later.

If you have all your 40000 objects already loaded in memory then you can just use code without clearing. Clearing on entity manager are used for optimising memory in PHP script. If you have enough memory to store all the objects you don't need to clear entity manager at all.

To optimise memory in that case you can unset($entity) after every persist.

And to fit DB connection bandwidth you can group several entities as in example.

$batchSize = 20;
for ($i = 1; $i <= 10000; ++$i) {
    $em->persist($entities[$i]);
    unset($entities[$i]);
    if (($i % $batchSize) === 0) {
        $em->flush();
    }
}
$em->flush(); //Persist objects that did not make up an entire batch
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!