2016-02-12 124 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