【问题标题】:Doctrine entitymanager clear doesn't fully clear学说 entitymanager clear 不完全清楚
【发布时间】:2013-09-28 00:11:36
【问题描述】:

我有这段代码:

$entityManager->clear('Reza\MyBundle\Entity\ListItem');

$identity = $entityManager->getUnitOfWork()->getIdentityMap();
foreach ($identity as $class => $objectlist) {
    if ($class == 'Reza\MyBundle\Entity\ListItem') {
        print "didn't fully clear, exiting..\n ";
        exit;
    }
}

您可能会认为,在我将类名传递给 clear 之后,您不应该再在工作单元中看到这些对象,但是通过查看源代码,我注意到当您将参数传递给 clear() 函数时仅分离该类型的实体。另一方面,如果我不向clear() 传递任何参数,它会分离并且实际上会清除,所以上面的代码不会到达第 138 行,退出。这意味着它不仅分离了所有实体,而且还清除了工作单元。

有人对此有任何想法吗?我应该向教义提交错误吗?

【问题讨论】:

    标签: php symfony doctrine-orm doctrine


    【解决方案1】:

    我想说,从技术上讲,这不是一个错误,因为 clear() 的工作原理与文档中所述相同,请参阅 Doctrine2 APIdocumentationsource code (current version)。

    clear() 方法只是detach() 指定类型的所有实体或实体的一种方式。 它可以被认为是“Multi-Detach”,它的目的并没有超越分离。

    当使用clear() 分离所有实体时,Doctrine 会使用最有效的方法分离实体。在此过程中,身份映射数组设置为空array()。 这将使我相信您所指的内容看起来已清除。

    $entityManager->clear();
    $identity = $entityManager->getUnitOfWork()->getIdentityMap(); 
    //This will return a an empty array() to $identity
    //therefore $identity['Reza\MyBundle\Entity\ListItem'] would be undefined
    

    如果我们假设为Reza\MyBundle\Entity\ListItem 的实体检索数据。 那么在下面的例子中我们可以看到工作单元至少有1个Reza\MyBundle\Entity\ListItem对象。

    $identity = $entityManager->getUnitOfWork()->getIdentityMap();
    $count = count($identity['Reza\MyBundle\Entity\ListItem']);
    // $count would be > 0;
    

    但是,当您使用 clear($entityName) 并按实体类型清除时,已清除/分离的实体会从工作单元中删除,仅保留数组键 [$entityName],而不保留任何对象。

    $entityManager->clear('Reza\MyBundle\Entity\ListItem');
    $identity = $entityManager->getUnitOfWork()->getIdentityMap(); 
    $count = count($identity['Reza\MyBundle\Entity\ListItem']);
    //$count would be == 0. All Objects cleared/detached.
    

    此功能由文档指定。

    我确实认为功能请求是有必要的,以使其工作更加一致。 当调用clear($entityName) Doctrine 时应该unset() 剩余的键,从而使其未定义(清除)。这将使我们能够更轻松地编写无论我们使用 clear() 还是 clear($entityName) 都可以工作的代码。

    【讨论】:

    • 一切都那么简单。它仅保留地图中类的名称,但实体消失了。干得好!
    • @hcoat 请不要将 (3) 链接到 GitHub 上 master 分支中的特定行,因为它很可能会改变(它已经改变了)。选择一个标记版本。
    • 有谁知道是否已经有一个功能请求来使这个功能更加一致?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-03
    • 2012-03-19
    相关资源
    最近更新 更多