Skip to content

Commit

Permalink
Merge pull request #285 from analogueorm/pr.281
Browse files Browse the repository at this point in the history
Query fix
  • Loading branch information
adrorocker authored Feb 11, 2020
2 parents 4c6cf3c + 07e67be commit e88a709
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 2 deletions.
22 changes: 20 additions & 2 deletions src/System/Query.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
18 changes: 18 additions & 0 deletions tests/cases/QueryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}

0 comments on commit e88a709

Please sign in to comment.