【发布时间】:2016-05-23 16:59:06
【问题描述】:
TL;DR:如何使用 Doctrine\ORM\EntityManager::clear() 和 $entityName?
假设我有一个带有Author 和Category 的Post 实体。我想将帖子添加到我的数据库(随机,来自 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);
}
}
由于我想清除 Posts,但又想保留 Author 和 Category 实体类型,我希望 $entityName = 'Acme\BlogBundle\Entity\Post'、$entityName = get_class($post); 或 $entityName = Acme\BlogBundle\Entity\Post::class 会有所帮助,但不幸的是它并没有清除任何内容。
如何正确使用这个参数?
【问题讨论】:
-
我猜你必须传递类似于
"AcmeBlogBundle:Post"的东西 -
@johnSmith 不,没有任何区别。
-
@TobiasXy 是的,我想是的。感谢您指出。
标签: php symfony doctrine-orm doctrine entitymanager