diff --git a/lib/Doctrine/Query.php b/lib/Doctrine/Query.php index dab7350aa..eec1a5d01 100644 --- a/lib/Doctrine/Query.php +++ b/lib/Doctrine/Query.php @@ -1249,15 +1249,23 @@ class Doctrine_Query extends Doctrine_Query_Abstract implements Countable // initialize temporary variables $where = $this->parts['where']; $having = $this->parts['having']; + $groupby = $this->parts['groupby']; $map = reset($this->_aliasMap); $componentAlias = key($this->_aliasMap); $table = $map['table']; - // build the query base $q = 'SELECT COUNT(DISTINCT ' . $this->getTableAlias($componentAlias) . '.' . $table->getIdentifier() - . ') FROM ' . $this->buildFromPart(); + . ')'; + + foreach ($this->parts['select'] as $field) { + if (strpos($field, '(') !== false) { + $q .= ', ' . $field; + } + } + + $q .= ' FROM ' . $this->buildFromPart(); // append column aggregation inheritance (if needed) $string = $this->applyInheritance(); @@ -1267,6 +1275,7 @@ class Doctrine_Query extends Doctrine_Query_Abstract implements Countable } // append conditions $q .= ( ! empty($where)) ? ' WHERE ' . implode(' AND ', $where) : ''; + $q .= ( ! empty($groupby)) ? ' GROUP BY ' . implode(', ', $groupby) : ''; $q .= ( ! empty($having)) ? ' HAVING ' . implode(' AND ', $having): ''; if ( ! is_array($params)) { diff --git a/tests/Query/SubqueryTestCase.php b/tests/Query/SubqueryTestCase.php index 33ea398d0..ab064e134 100644 --- a/tests/Query/SubqueryTestCase.php +++ b/tests/Query/SubqueryTestCase.php @@ -108,7 +108,7 @@ class Doctrine_Query_Subquery_TestCase extends Doctrine_UnitTestCase $this->assertEqual($q->getSql(), 'SELECT e.id AS e__id, e.name AS e__name, COUNT(DISTINCT a.id) AS a__0 FROM entity e LEFT JOIN album a ON e.id = a.user_id WHERE e.id IN (SELECT DISTINCT e2.id FROM entity e2 LEFT JOIN album a2 ON e2.id = a2.user_id WHERE (e2.type = 0) GROUP BY e2.id ORDER BY a__0 LIMIT 5) AND (e.type = 0) GROUP BY e.id ORDER BY a__0'); } - + public function testAggregateFunctionsInOrderByAndHavingWithCount() { $q = new Doctrine_Query(); @@ -123,8 +123,8 @@ class Doctrine_Query_Subquery_TestCase extends Doctrine_UnitTestCase try { $q->count(); + $this->pass(); } catch (Doctrine_Exception $e) { - $this->fail(); } }