diff --git a/application/Espo/Core/Formula/Functions/RecordGroup/FindRelatedOneType.php b/application/Espo/Core/Formula/Functions/RecordGroup/FindRelatedOneType.php index 1dc268236f..dda25ad6db 100644 --- a/application/Espo/Core/Formula/Functions/RecordGroup/FindRelatedOneType.php +++ b/application/Espo/Core/Formula/Functions/RecordGroup/FindRelatedOneType.php @@ -80,6 +80,18 @@ class FindRelatedOneType extends \Espo\Core\Formula\Functions\Base $metadata = $this->getInjection('metadata'); + $relationType = $entity->getRelationParam($link, 'type'); + + if (in_array($relationType, ['belongsTo', 'hasOne', 'belongsToParent'])) { + $relatedEntity = $entityManager->getRepository($entityType)->findRelated($entity, $link, [ + 'select' => ['id'], + ]); + if (!$relatedEntity) { + return null; + } + return $relatedEntity->id; + } + if (!$orderBy) { $orderBy = $metadata->get(['entityDefs', $entityType, 'collection', 'orderBy']); if (is_null($order)) { @@ -89,8 +101,6 @@ class FindRelatedOneType extends \Espo\Core\Formula\Functions\Base $order = $order ?? 'asc'; } - $relationType = $entity->getRelationParam($link, 'type'); - $foreignEntityType = $entity->getRelationParam($link, 'entity'); if (!$foreignEntityType) throw new Error("Formula record\\findRelatedOne: Bad or not supported link '{$link}'."); @@ -100,7 +110,6 @@ class FindRelatedOneType extends \Espo\Core\Formula\Functions\Base $selectManager = $this->getInjection('selectManagerFactory')->create($foreignEntityType); $selectParams = $selectManager->getEmptySelectParams(); - if ($relationType === 'hasChildren') { $selectParams['whereClause'][] = [$foreignLink . 'Id' => $entity->id]; $selectParams['whereClause'][] = [$foreignLink . 'Type' => $entity->getEntityType()]; diff --git a/tests/integration/Espo/Core/Formula/FormulaTest.php b/tests/integration/Espo/Core/Formula/FormulaTest.php index 00da752dd8..ec75dcd8d7 100644 --- a/tests/integration/Espo/Core/Formula/FormulaTest.php +++ b/tests/integration/Espo/Core/Formula/FormulaTest.php @@ -313,6 +313,23 @@ class FormulaTest extends \tests\integration\Core\BaseTestCase $this->assertEquals($c2->id, $result); } + public function testRecordFindRelatedOne1() + { + $fm = $this->getContainer()->get('formulaManager'); + $em = $this->getContainer()->get('entityManager'); + + $a = $em->createEntity('Account', [ + ]); + + $o = $em->createEntity('Opportunity', [ + 'accountId' => $a->id, + ]); + + $script = "record\\findRelatedOne('Opportunity', '".$o->id."', 'account')"; + $result = $fm->run($script); + $this->assertEquals($a->id, $result); + } + public function testRecordAttribute() { $fm = $this->getContainer()->get('formulaManager');