From 40beaa8ccd56e8097e3a25b091f77625896c286e Mon Sep 17 00:00:00 2001 From: Deus Kane Date: Mon, 2 Sep 2019 11:25:44 +0100 Subject: [PATCH 1/2] Changed query object to be able to recognise an aliased primary key --- src/System/Query.php | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/src/System/Query.php b/src/System/Query.php index 3c061f2..a145a09 100755 --- a/src/System/Query.php +++ b/src/System/Query.php @@ -583,8 +583,26 @@ public function getEagerLoads() */ protected function enforceIdColumn($columns) { - if (!in_array($this->entityMap->getKeyName(), $columns)) { - $columns[] = $this->entityMap->getKeyName(); + $primaryKey = $this->entityMap->getKeyName(); + $escapedKeyName = preg_quote($primaryKey, '/'); + $table = $this->entityMap->getTable(); + + $match = false; + + foreach ($columns as $column) { + if (substr($column, -strlen($primaryKey)) === $primaryKey) { + if (strlen($column) === strlen($primaryKey)) { + $match = true; + break; + } elseif (preg_match("/\w+\s+(?:(?:(AS|as)\s+)?$escapedKeyName/", $column)) { + $match = true; + break; + } + } + } + + if (!$match) { + $columns[] = "$table.$primaryKey AS $primaryKey"; } return $columns; From 7001d07e995d9730bc7e9110f9fe258e9d79ab76 Mon Sep 17 00:00:00 2001 From: Deus Kane Date: Mon, 2 Sep 2019 11:58:05 +0100 Subject: [PATCH 2/2] Added test for aliasing --- tests/cases/QueryTest.php | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/tests/cases/QueryTest.php b/tests/cases/QueryTest.php index 5df10b8..4d3df5c 100644 --- a/tests/cases/QueryTest.php +++ b/tests/cases/QueryTest.php @@ -98,4 +98,22 @@ public function test_pluck() $this->assertEquals([$blogA->id, $blogB->id], $ids->all()); } + + public function test_alias() + { + $user = $this->factoryCreateUid(User::class); + /** @var \Analogue\ORM\System\Mapper $userMapper */ + $userMapper = $this->mapper($user); + $userMapper->store($user); + $userTable = $userMapper->getEntityMap()->getTable(); + $primaryKey = $userMapper->getEntityMap()->getKeyName(); + $this->clearCache(); + + $query = $userMapper->getQuery(); + $query->select(["$userTable.$primaryKey as $primaryKey", 'identity_firstname', 'identity_lastname']); + $results = $query->get(); + + $this->assertCount(1, $results); + $this->assertEquals($user->id, $results->first()->id); + } }