Let’s assume we have an entity retrieved from the database with two fields: first name and last name.
Now, we will modify these fields.
$entity
->setFirstName('Tadeusz')
->setLastName('Kowalski')
;We aren’t triggering a flush yet.
We retrieve the UnitOfWork from the entityManager and check:
$uow = $em->getUnitOfWork();
$originalEntityData = $uow->getOriginalEntityData($entity);After dumping the result, we get the entire entity in its pre-modification state, something roughly like this:
array:20 [▼
"id" => 74
"firstName" => "Bogdan"
"lastName" => "Userski"
"description" => null
"createdAt" => DateTimeImmutable @1771500229 {#990 ▶}
"updatedAt" => DateTimeImmutable @1773146042 {#992 ▶}
"user_id" => 75
"user" =>
App\Entity\User
\
User
{#995 ▶}
]And if we are only interested in the fields that have changed, showing both the old and new versions.
$uow->computeChangeSets();
$changeSets = $uow->getEntityChangeSet($entity);Note: Remember to call computeChangeSets before retrieving data via getEntityChangeSet, otherwise, it returns an empty array.
array:2 [▼
"firstName" => array:2 [▼
0 => "Bogdan"
1 => "Tadeusz"
]
"lastName" => array:2 [▼
0 => "Userski"
1 => “Kowalski"
]
]The computeChangeSets command can be costly when there are many modified entities, yet we are interested in changes to only one. In such cases, it is better to call it by specifying the entity of interest:
$uow = $em->getUnitOfWork();
$meta = $em->getClassMetadata($entity::class);
$uow->computeChangeSet($meta, $entity);
$changeSets = $uow->getEntityChangeSet($entity);

Leave a Reply