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; 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); + } }