Skip to content

Commit

Permalink
Merge pull request #7 from martok/select-alias
Browse files Browse the repository at this point in the history
Add alias support for select in SQL builder
  • Loading branch information
nicksagona authored Oct 27, 2023
2 parents aba3ebb + 17480bd commit 19904bf
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 0 deletions.
7 changes: 7 additions & 0 deletions src/Sql/Select.php
Original file line number Diff line number Diff line change
Expand Up @@ -455,6 +455,13 @@ public function render(): string
// Else, if there is a nested SELECT statement.
} else if ($this->table instanceof \Pop\Db\Sql\Select) {
$sql .= (string)$this->table;
// Else, if there is an aliased table
} else if (is_array($this->table)) {
if (count($this->table) !== 1)
throw new Exception('Error: Only one table can be used in FROM clause.');
$alias = array_key_first($this->table);
$table = $this->table[$alias];
$sql .= $this->quoteId($table) . ' AS ' . $this->quoteId($alias);
// Else, just select from the table
} else {
$sql .= $this->quoteId($this->table);
Expand Down
7 changes: 7 additions & 0 deletions tests/Sql/SelectTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,13 @@ public function testAlias()
$this->db->disconnect();
}

public function testTableAlias()
{
$sql = $this->db->createSql();
$sql->select(['u.username'])->from(['u' => 'users']);
$this->assertEquals('SELECT `u`.`username` FROM `users` AS `u`', $sql->render());
}

public function testJoin()
{
$sql = $this->db->createSql();
Expand Down

0 comments on commit 19904bf

Please sign in to comment.