From 26b245d78787c8db3067b6351bc8e9b5128505f1 Mon Sep 17 00:00:00 2001 From: Johannes Meyer Date: Thu, 11 Jan 2024 16:52:50 +0100 Subject: [PATCH] Hydrator: Properly hydrate custom columns if an alias prefix is used fixes #127 --- src/Hydrator.php | 4 ++++ tests/HydratorTest.php | 21 +++++++++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/src/Hydrator.php b/src/Hydrator.php index ef7730e..63b3ff2 100644 --- a/src/Hydrator.php +++ b/src/Hydrator.php @@ -151,6 +151,10 @@ public function hydrate(array $data, Model $model) // If there are any columns left, propagate them to the targeted relation if possible, to the base otherwise foreach ($data as $column => $value) { + if (($aliasPrefix = $this->query->getResolver()->getAliasPrefix())) { + $column = substr($column, strlen($aliasPrefix)); + } + $columnName = $column; $steps = explode('_', $column); $baseTable = array_shift($steps); diff --git a/tests/HydratorTest.php b/tests/HydratorTest.php index cbcfe6c..a2dfec6 100644 --- a/tests/HydratorTest.php +++ b/tests/HydratorTest.php @@ -87,4 +87,25 @@ public function testCustomAliasesForTheBaseTableAndRelationsWithUnderscoresInThe 'Custom aliases for relations are not correctly hydrated if their name contains an underscore' ); } + + public function testCustomColumnsAreProperlyHydratedIfAnAliasPrefixIsUsed() + { + $query = Car::on(new TestConnection()); + $query->getResolver()->setAliasPrefix('test_'); + + $hydrator = $query->createHydrator(); + + $subject = new Car(); + $hydrator->hydrate(['test_car_wheel_size' => 'xxl'], $subject); + + $this->assertTrue( + isset($subject->wheel_size), + 'Custom columns are not correctly hydrated if an alias prefix is in use' + ); + $this->assertSame( + 'xxl', + $subject->wheel_size, + 'Custom columns are not correctly hydrated if an alias prefix is in use' + ); + } }