Skip to content
Permalink
Browse files

Implementing group()

  • Loading branch information...
lorenzo committed Jan 8, 2013
1 parent d992bfe commit d14e67b34cda1d3fe111dee9196fad881db7e77b
@@ -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;
}
@@ -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.
You can’t perform that action at this time.