检查实体是否已经持久保存到Symfony2中的EntityManager

时间:2014-07-16 08:38:00

标签: symfony doctrine entitymanager

在Symfony2中,是否可以检查特定实体是否已经存在且存在于EntityManager中?

我正在处理一些数据导入,而某些记录可能完全相同。我正在进行批量插入,即仅在持久保留一定数量的实体后才调用flush()。所以,我需要检查我试图保持的实体是否已经不在EntityManager中了。

2 个答案:

答案 0 :(得分:7)

是的,你应该使用工作单位http://phpdox.de/demo/Symfony2/classes/Doctrine_ORM_UnitOfWork.xhtml#isEntityScheduled

$uow = $this->getDoctrine()->getManager()->getUnitOfWork()
$exist =  $uow->isEntityScheduled(  $entity );

答案 1 :(得分:0)

您可以在对象中添加序列化方法,该方法会在模型中创建相关数据的字符串,如...

public function serialize()
{
    return serialize(array(
        $this->field1,
        $this->field2,
        .. etc ..
    ));
}

然后继续使用预定的实体插入来检查序列化数据之前是否已被使用过..

$uow = $this->getDoctrine()->getManager()->getUnitOfWork()
$insertions = $uow->getScheduledEntityInsertions();

$insertions = new ArrayCollection($insertions);

$scheduled = $insertions->filter(
        function(YourModel $model) use ($new) {
            return $model->serialize() === $new->serialize();
        }
    )->first();
// This will either return the relevant model or false
相关问题