【问题标题】:EntityManager: only clear entities of a certain typeEntityManager:只清除某种类型的实体
【发布时间】:2016-05-23 16:59:06
【问题描述】:

TL;DR:如何使用 Doctrine\ORM\EntityManager::clear()$entityName

假设我有一个带有AuthorCategoryPost 实体。我想将帖子添加到我的数据库(随机,来自 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


【解决方案1】:

您可以将类名作为 entityName 传递给 entitymanager clear 方法,但它必须与存储在他的身份映射中的学说工作单元完全相同。为了得到正确的,你应该这样做:

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

【讨论】:

  • $entityName 返回Acme\BlogBundle\Entity\Post,所以很遗憾它也没有用。
  • 对我来说,你的记忆问题似乎是由不同的东西引起的。如果您使用 symfony 控制台命令,请确保使用 --env=prod 以避免记录缓冲区
  • 至少,如果您只需要实体在数据库上建立关系,您可以使用 $em->getReference($entityName, $id) 可以节省一些时间
猜你喜欢
  • 1970-01-01
  • 2015-07-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多