Skip to content
Advertisement

Do I have to persist object from repository in Doctrine?

Do I have to persist the object I fetched from a repository? For example:

$foo = $this->repository->find($id);
$foo->setBar($baz);

$this->flush();

Do I have to add $this->persist($foo);? When I don’t have to persist changes?

Advertisement

Answer

If this is doctrine repository, the entity it finds is already managed so you dont have to call persist(). You call persist on entities that are not yet managed by enytityManager so in most of the cases it is for new objects that you want to store.

This wont save the User to the database

$user = new User;
$user->setName('Mr.Right');
$em->flush();

This will

$user = new User;
$user->setName('Mr.Right');
$em->persist($user);
$em->flush();

The entities you later fetch are already managed so in your code the change will be flushed.

https://www.doctrine-project.org/projects/doctrine-orm/en/2.7/reference/working-with-objects.html#persisting-entities

An entity can be made persistent by passing it to the EntityManager#persist($entity) method. By applying the persist operation on some entity, that entity becomes MANAGED, which means that its persistence is from now on managed by an EntityManager. As a result the persistent state of such an entity will subsequently be properly synchronized with the database when EntityManager#flush() is invoked.

You can verify this by calling EntityManager->contains($entity) to see if this entity is managed by EM, in your case it should already show that it is. For new entities only after persisting.

You asked:

When I don’t have to persist changes?

Its not about persisting changes, its about making entity itself persistent.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement