Skip to content

Commit

Permalink
Implementing group()
Browse files Browse the repository at this point in the history
  • Loading branch information
lorenzo committed Jan 8, 2013
1 parent d992bfe commit d14e67b
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 2 deletions.
13 changes: 11 additions & 2 deletions lib/Cake/Model/Datasource/Database/Query.php
Expand Up @@ -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;
}

Expand Down
36 changes: 36 additions & 0 deletions lib/Cake/Test/TestCase/Model/Datasource/Database/QueryTest.php
Expand Up @@ -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);
}

}

0 comments on commit d14e67b

Please sign in to comment.