diff --git a/lib/Cake/Model/Datasource/Database/Query.php b/lib/Cake/Model/Datasource/Database/Query.php index 2cbe54baf8d..43a1b4748e7 100644 --- a/lib/Cake/Model/Datasource/Database/Query.php +++ b/lib/Cake/Model/Datasource/Database/Query.php @@ -89,7 +89,7 @@ public function sql() { if (!count($parts)) { return; } - if ($parts instanceof QueryExpression || $parts instanceof self) { + if ($parts instanceof QueryExpression) { $parts = [$parts->sql()]; } if (isset($this->_templates[$name])) { @@ -433,7 +433,7 @@ protected function _bindParams($statement) { * @return string **/ public function __toString() { - return $this->sql(); + return sprintf('(%s)', $this->sql()); } } diff --git a/lib/Cake/Test/TestCase/Model/Datasource/Database/QueryTest.php b/lib/Cake/Test/TestCase/Model/Datasource/Database/QueryTest.php index 3810d3f5b6a..c0c601e5ef8 100644 --- a/lib/Cake/Test/TestCase/Model/Datasource/Database/QueryTest.php +++ b/lib/Cake/Test/TestCase/Model/Datasource/Database/QueryTest.php @@ -1265,4 +1265,27 @@ public function testSelectOffset() { $this->assertEquals(['id' => 3], $result->fetch('assoc')); } + public function testSuqueryInSelect() { + $this->_insertDateRecords(); + $this->_insertTwoRecords(); + + $query = new Query($this->connection); + $subquery = (new Query($this->connection)) + ->select('name') + ->from(['b' => 'authors']) + ->where(['b.id = a.id']); + $result = $query + ->select(['id', 'name' => $subquery]) + ->from(['a' => 'dates'])->execute(); + + $expected = [ + ['id' => 1, 'name' => 'Chuck Norris'], + ['id' => 2, 'name' => 'Bruce Lee'], + ['id' => 3, 'name' => null] + ]; + $this->assertEquals($expected, $result->fetchAll('assoc')); + + + } + }