How to Track Entity Changes in Doctrine 2?

Patricia Arquette
Release: 2024-11-10 09:19:02
Original
267 people have browsed it

How to Track Entity Changes in Doctrine 2?

Tracking Entity Changes in Doctrine 2

Doctrine 2 provides a way to track the changed fields of an entity using the EntityManager and UnitOfWork.

Suppose you have an entity $e and modify its fields:

$e->setFoo('a');
$e->setBar('b');
Copy after login

To retrieve an array of changed fields:

  1. Obtain the UnitOfWork:

    $uow = $em->getUnitOfWork();
    Copy after login
  2. Compute Changes:

    $uow->computeChangeSets();
    Copy after login
  3. Get Entity Changes:

    $changeset = $uow->getEntityChangeSet($e);
    Copy after login

The $changeset will contain all modified attribute-value pairs:

[
    'foo' => ['old' => 'oldFoo', 'new' => 'a'],
    'bar' => ['old' => 'oldBar', 'new' => 'b'],
]
Copy after login

Note for PreUpdate Listeners:

If attempting to retrieve updated fields within a preUpdate listener, skip the change set computation as it has already occurred. Simply call getEntityChangeSet to retrieve the changes.

Warning:

Using this method outside of Doctrine event listeners can disrupt its operation.

The above is the detailed content of How to Track Entity Changes in Doctrine 2?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template