diff --git a/lib/Cake/Model/Datasource/Database/Query.php b/lib/Cake/Model/Datasource/Database/Query.php index 542190c1e0a..c618876e1e4 100644 --- a/lib/Cake/Model/Datasource/Database/Query.php +++ b/lib/Cake/Model/Datasource/Database/Query.php @@ -338,8 +338,17 @@ protected function _buildOrderPart($parts) { return sprintf (' ORDER BY %s', implode(', ', $order)); } - public function group($field, $overwrite = true) { - $this->_parts['group'][] = $field; + public function group($fields, $overwrite = false) { + if ($overwrite) { + $this->_parts['group'] = []; + } + + if (!is_array($fields)) { + $fields = [$fields]; + } + + $this->_parts['group'] = array_merge($this->_parts['group'], array_values($fields)); + $this->_dirty = true; return $this; } diff --git a/lib/Cake/Test/TestCase/Model/Datasource/Database/QueryTest.php b/lib/Cake/Test/TestCase/Model/Datasource/Database/QueryTest.php index 8ebf2f89645..1e730cf735d 100644 --- a/lib/Cake/Test/TestCase/Model/Datasource/Database/QueryTest.php +++ b/lib/Cake/Test/TestCase/Model/Datasource/Database/QueryTest.php @@ -1022,4 +1022,40 @@ public function testSelectOrderBy() { $this->assertEquals(['id' => 5], $result->fetch('assoc')); } +/** + * Tests that group by fields can be passed similar to select fields + * and that it sends the correct query to the database + * + * @return void + **/ + public function testSelectGroup() { + $statement = $this->_insertTwoRecords(); + $statement->bindValue(1, 3); + $statement->bindValue(2, 'another title'); + $statement->bindValue(3, 'another body'); + $statement->bindValue(4, 2); + $statement->execute(); + + $query = new Query($this->connection); + $result = $query + ->select(['total' => 'count(author_id)', 'author_id']) + ->from('articles') + ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => 'author_id = a.id']) + ->group('author_id') + ->execute(); + $expected = [['total' => 1, 'author_id' => 1], ['total' => '2', 'author_id' => 2]]; + $this->assertEquals($expected, $result->fetchAll('assoc')); + + $result = $query->select(['total' => 'count(title)', 'author_id'], true) + ->group(['name'], true) + ->execute(); + $expected = [['total' => 2, 'author_id' => 2], ['total' => 1, 'author_id' => 1]]; + $this->assertEquals($expected, $result->fetchAll('assoc')); + + $result = $query->select(['articles.id']) + ->group(['articles.id']) + ->execute(); + $this->assertCount(3, $result); + } + }