diff --git a/src/Reference/HasOneSql.php b/src/Reference/HasOneSql.php index d1476258b..fe9ea46e9 100644 --- a/src/Reference/HasOneSql.php +++ b/src/Reference/HasOneSql.php @@ -64,11 +64,12 @@ private function _addField(string $fieldName, bool $theirFieldIsTitle, ?string $ return $fieldExpression; } - private function getLinkNameWithoutIdSuffix(): string + private function getLinkNameWithoutReferenceSuffix(Model $theirModel): string { $ourModel = $this->getOurModel(); + $theirFieldName = $this->getTheirFieldName($theirModel); - return preg_replace('~_(' . preg_quote($ourModel->idField, '~') . '|id)$~', '', $this->link); + return preg_replace('~_(' . preg_quote($theirFieldName, '~') . '|' . preg_quote($ourModel->idField, '~') . '|id)$~', '', $this->link); } private function getOurFieldCaptionWithoutReferenceSuffix(Model $theirModel): string @@ -182,7 +183,10 @@ public function refLink(array $defaults = []): Model */ public function addTitle(array $defaults = []): SqlExpressionField { - $fieldName = $defaults['field'] ?? $this->getLinkNameWithoutIdSuffix(); + $ourModel = $this->getOurModel(); + $analysingTheirModel = $ourModel->getReference($this->link)->createAnalysingTheirModel(); + + $fieldName = $defaults['field'] ?? $this->getLinkNameWithoutReferenceSuffix($analysingTheirModel); $defaults['ui'] = array_merge(['visible' => true], $defaults['ui'] ?? [], ['editable' => false]); diff --git a/tests/ReferenceSqlTest.php b/tests/ReferenceSqlTest.php index bed66c1a4..184058b3c 100644 --- a/tests/ReferenceSqlTest.php +++ b/tests/ReferenceSqlTest.php @@ -788,10 +788,10 @@ public function testAddTitleWholeIdField(): void $o->addField('amount'); $o->hasOne('user_id', ['model' => $u]); - $titleField = $o->getReference('user_id')->addTitle(); + $referencedTitleField = $o->getReference('user_id')->addTitle(); - self::assertSame('user', $titleField->shortName); - self::assertSame('User', $titleField->getCaption()); + self::assertSame('user', $referencedTitleField->shortName); + self::assertSame('User', $referencedTitleField->getCaption()); } /** @@ -981,6 +981,16 @@ public function testHasOneReferenceCaptionNonIdField(): void $referencedCaption = $o->getField('user_last_name')->getCaption(); self::assertSame('User Surname', $referencedCaption); + + $referencedTitleField = $orderUserRef->addTitle(); + self::assertSame('my_user', $referencedTitleField->shortName); + self::assertSame('My User', $referencedTitleField->getCaption()); + + $orderUserRef2 = $o->hasOne('my_user2_name', ['model' => $u, 'ourField' => 'user_name', 'theirField' => 'name']); + $referenced2TitleField = $orderUserRef2->addTitle(); + + self::assertSame('my_user2', $referenced2TitleField->shortName); + self::assertSame('My User 2', $referenced2TitleField->getCaption()); } /**