From 011b55119b56023224781be01d27043c5a1454ab Mon Sep 17 00:00:00 2001 From: Jamie Matthews Date: Mon, 25 Oct 2010 20:21:52 +0100 Subject: Add table_alias method to provide ability to alias the main table in SELECT queries --- idiorm.php | 17 ++++++++++++++++- test/test_queries.php | 3 +++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/idiorm.php b/idiorm.php index c65fdd5..6087705 100644 --- a/idiorm.php +++ b/idiorm.php @@ -80,6 +80,9 @@ // The name of the table the current ORM instance is associated with protected $_table_name; + // Alias for the table to be used in SELECT queries + protected $_table_alias = null; + // Values to be bound to the query protected $_values = array(); @@ -361,6 +364,14 @@ return $this; } + /** + * Add a an alias for the main table to be used in SELECT queries + */ + public function table_alias($alias) { + $this->_table_alias = $alias; + return $this; + } + /** * Internal method to add an unquoted expression to the set * of columns returned by the SELECT query. The second optional @@ -668,7 +679,11 @@ */ protected function _build_select_start() { $result_columns = join(', ', $this->_result_columns); - return "SELECT {$result_columns} FROM " . $this->_quote_identifier($this->_table_name); + $fragment = "SELECT {$result_columns} FROM " . $this->_quote_identifier($this->_table_name); + if (!is_null($this->_table_alias)) { + $fragment .= " " . $this->_quote_identifier($this->_table_alias); + } + return $fragment; } /** diff --git a/test/test_queries.php b/test/test_queries.php index d72c101..807eed6 100644 --- a/test/test_queries.php +++ b/test/test_queries.php @@ -147,6 +147,9 @@ $expected = "SELECT * FROM `widget` JOIN `widget_handle` ON `widget_handle`.`widget_id` = `widget`.`id` JOIN `widget_nozzle` ON `widget_nozzle`.`widget_id` = `widget`.`id`"; Tester::check_equal("Multiple join sources", $expected); + ORM::for_table('widget')->table_alias('w')->find_many(); + $expected = "SELECT * FROM `widget` `w`"; + ORM::for_table('widget')->join('widget_handle', array('wh.widget_id', '=', 'widget.id'), 'wh')->find_many(); $expected = "SELECT * FROM `widget` JOIN `widget_handle` `wh` ON `wh`.`widget_id` = `widget`.`id`"; Tester::check_equal("Join with alias", $expected); -- cgit v1.2.3