diff --git a/application/Espo/ORM/BaseEntity.php b/application/Espo/ORM/BaseEntity.php index 75a7d95570..a01684c238 100644 --- a/application/Espo/ORM/BaseEntity.php +++ b/application/Espo/ORM/BaseEntity.php @@ -594,7 +594,7 @@ class BaseEntity implements Entity } /** - * Set as not new. Meaning an entity is fetched or already saved. + * Set as not new. Meaning the entity is fetched or already saved. */ public function setAsNotNew(): void { diff --git a/application/Espo/ORM/Entity.php b/application/Espo/ORM/Entity.php index 97b78b285c..0d251f8558 100644 --- a/application/Espo/ORM/Entity.php +++ b/application/Espo/ORM/Entity.php @@ -138,12 +138,18 @@ interface Entity public function isNew(): bool; /** - * Whether is fetched from DB. + * Set an entity as fetched. All current attribute values will be set as those that are fetched + * from the database. + */ + public function setAsFetched(): void; + + /** + * Whether is fetched from the database. */ public function isFetched(): bool; /** - * Whether an attribute was changed (since syncing with DB). + * Whether an attribute was changed (since syncing with the database). */ public function isAttributeChanged(string $name): bool; diff --git a/application/Espo/ORM/EntityManager.php b/application/Espo/ORM/EntityManager.php index e393003646..1f94bf25bb 100644 --- a/application/Espo/ORM/EntityManager.php +++ b/application/Espo/ORM/EntityManager.php @@ -292,6 +292,32 @@ class EntityManager $this->getRepository($entityType)->remove($entity, $options); } + /** + * Refresh an entity from the database, overwriting made changes, if any. + * Can be used to fetch attributes that were not fetched initially. + * + * @throws RuntimeException + */ + public function refreshEntity(Entity $entity): void + { + if ($entity->isNew()) { + throw new RuntimeException("Can't refresh a new entity."); + } + + if ($entity->getId() === null) { + throw new RuntimeException("Can't refresh an entity w/o ID."); + } + + $fetchedEntity = $this->getEntity($entity->getEntityType(), $entity->getId()); + + if (!$fetchedEntity) { + throw new RuntimeException("Can't refresh a non-existent entity."); + } + + $entity->set($fetchedEntity->getValueMap()); + $entity->setAsFetched(); + } + /** * Create entity (and store to database). * diff --git a/tests/integration/Espo/ORM/EntityManager.php b/tests/integration/Espo/ORM/EntityManager.php new file mode 100644 index 0000000000..7bbbdf7d9c --- /dev/null +++ b/tests/integration/Espo/ORM/EntityManager.php @@ -0,0 +1,53 @@ +createApplication(); + + /** @var EntityManager $em */ + $em = $app->getContainer()->get('entityManager'); + + $entity = $em->createEntity('Account', [ + 'name' => 'Test', + ]); + + $entity->set('name', 'Hello'); + + $em->refreshEntity($entity); + + $this->assertEquals('Test', $entity->get('name')); + } +}