When mapping data to an existing object that contains collections (e.g., a User with multiple Address objects), AutoMapper can reuse existing objects within those collections instead of always instantiating new ones. This prevents duplicate entries in databases or ORM exceptions when dealing with existing entities.
To enable this, AutoMapper uses the concept of an Identifier. When mapping a collection, AutoMapper checks the destination collection for objects with matching identifiers. If a match is found, the existing object is updated; otherwise, a new object is created and added to the collection.
// Fetch existing object from database
$user = $this->entityManager->find(User::class, $id);
// Map data to the existing object
// AutoMapper will use identifiers to manage nested collections
$mapper->map($requestValue, $user);