How to determine if a Doctrine entity is persisted

2019-03-09 17:15发布

Is there a way to determine if a parameter is an object that is already persisted by Doctrine or not? Something like an entity manager method that checks that an object is not a plain old object but actually something already in memory/persisted.

<?php
public function updateStatus(Entity $entity, EntityStatus $entityStatus)
{
    $entityManager = $this->getEntityManager();
    try {
        // checking persisted entity
        if (!$entityManager->isPersisted($entity)) { 
            throw new InvalidArgumentException('Entity is not persisted');
        }
        // ...
    } catch (InvalidArgumentException $e) {
    }
}

3条回答
Deceive 欺骗
2楼-- · 2019-03-09 17:19

EDIT: As said by @Andrew Atkinson, it seems

EntityManager->contains($entity)

is the preferred way now.

Previous answer: You have to use UnitOfWork api like this:

$isPersisted = \Doctrine\ORM\UnitOfWork::STATE_MANAGED === $entityManager->getUnitOfWork()->getEntityState($entity);
查看更多
手持菜刀,她持情操
3楼-- · 2019-03-09 17:32

An Easier and more robust way to check if the entity is flushed or not, just check for the ID.

if (!$entity->getId()) {

    echo 'new entity';

} else { 

    echo 'already persisted entity';

}

This solution is very much dependant on the case, but it may be the best for you


edit:

From comments it appears this is not the most relevant answer, however may provide useful for someone as it is closely related to the question.

查看更多
三岁会撩人
4楼-- · 2019-03-09 17:36

The EntityManager method contains serves this purpose. See the documentation (2.4).

In Doctrine 2.4, the implementation looks like this:

class EntityManager {
// ...
public function contains($entity)
{
    return $this->unitOfWork->isScheduledForInsert($entity)
        || $this->unitOfWork->isInIdentityMap($entity)
        && ! $this->unitOfWork->isScheduledForDelete($entity);
}
查看更多
登录 后发表回答