2016-02-12 43 views
3

TL明確的實體; DR:我如何使用Doctrine\ORM\EntityManager::clear()使用$entityName的EntityManager:只有某些類型的

比方說,我有一個Post實體與AuthorCategory。我想添加帖子到我的數據庫(隨機,從CSV文件或任何)。我在添加數據時遇到性能問題。內存使用增加,並減慢了進程,但我不知道如何(部分)清除EntityManager。

這就是魔法發生循環:

$batchSize = 250; 
foreach ($posts as $post) { 
    //$post['author'] is instance of Acme\BlogBundle\Author 
    $post = new Post($post['author'], $post['category']); 
    $em->persist($post); 

    if ($i % $batchSize == 0) { 
     $entity = '??'; 
     $em->flush(); 
     $em->clear($entityName); 

     gc_collect_cycles(); 
    } 
} 

這將引發Doctrine\ORM\ORMInvalidArgumentException: A new entity was found through the relationship Acme\BlogBundle\Post#author。這是正確的,因爲Author是由已被清除EntityManager管理的。

這是明確的方法:

namespace Doctrine\ORM; 
class EntityManager implements EntityManagerInterface { 
/** 
* Clears the EntityManager. All entities that are currently managed 
* by this EntityManager become detached. 
* 
* @param string|null $entityName if given, only entities of this type will get detached 
* 
* @return void 
*/ 
public function clear($entityName = null) 
{ 
    $this->unitOfWork->clear($entityName); 
} 

} 

因爲我要清除的帖子,但要保留作者和類別實體類型,我預計$entityName = 'Acme\BlogBundle\Entity\Post'$entityName = get_class($post);$entityName = Acme\BlogBundle\Entity\Post::class會有所幫助,但不幸的是它不清除任何東西。

如何正確使用這個參數?

+0

我猜你必須通過某事類同'「AcmeBlogBu​​ndle:郵報」' –

+1

可能的重複http://stackoverflow.com/questions/19061870/doctrine-entitymanager-clear-doesnt-fully-clear? –

+0

@johnSmith不,沒有任何區別。 –

回答

0

您可以通過一個類名作爲的entityName到EntityManager的明確的方法,但它必須是完全一樣的工作原則單位已存儲在他的身份映射。爲了得到合適的人,你應該做這樣的事情:

$classMetadata = $em->getClassMetadata(get_class($post)); 
$entityName = $classMetadata->rootEntityName; 
+0

'$ entityName'返回'的Acme \ BlogBu​​ndle \實體\ POST',所以很遺憾它也不能工作。 –

+1

對我而言,看起來,你的記憶問題可能是由不同的事情引起的。 如果您正在使用的symfony控制檯命令,請確保使用--env =督促避免日誌緩衝區 – Gladhon

+1

至少,如果你只需要實體,使您的數據庫關係,你可以使用$ EM-> getReference($的entityName, $ id)可以節省一些時間 – Gladhon