Skip to content

Commit

Permalink
Added virtual field support for GROUP BY.
Browse files Browse the repository at this point in the history
  • Loading branch information
Phally authored and lorenzo committed Jan 11, 2010
1 parent dda2414 commit bbb105f
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 2 deletions.
9 changes: 7 additions & 2 deletions cake/libs/model/datasources/dbo_source.php 100644 → 100755
Expand Up @@ -1413,7 +1413,7 @@ function buildStatement($query, &$model) {
'order' => $this->order($query['order'], 'ASC', $model),
'limit' => $this->limit($query['limit'], $query['offset']),
'joins' => implode(' ', $query['joins']),
'group' => $this->group($query['group'])
'group' => $this->group($query['group'], $model)
));
}

Expand Down Expand Up @@ -2328,9 +2328,14 @@ function order($keys, $direction = 'ASC', $model = null) {
* @return mixed string condition or null
* @access public
*/
function group($group) {
function group($group, &$model = null) {
if ($group) {
if (is_array($group)) {
foreach($group as $index => $key) {
if ($model->isVirtualField($key)) {
$group[$index] = '(' . $model->getVirtualField($key) . ')';
}
}
$group = implode(', ', $group);
}
return ' GROUP BY ' . $this->__quoteFields($group);
Expand Down
23 changes: 23 additions & 0 deletions cake/tests/cases/libs/model/model_read.test.php 100644 → 100755
Expand Up @@ -7240,6 +7240,29 @@ function testVirtualFields() {
$Post->virtualFields = array('other_field' => 'COUNT(Post.id) + 1');
$result = $Post->field('other_field');
$this->assertEqual($result, 4);

ClassRegistry::flush();
$Post = ClassRegistry::init('Post');

$Post->create();
$Post->virtualFields = array(
'year' => 'YEAR(Post.created)',
'unique_test_field' => 'COUNT(Post.id)'
);

$expectation = array(
'Post' => array(
'year' => 2007,
'unique_test_field' => 3
)
);

$result = $Post->find('first', array(
'fields' => array_keys($Post->virtualFields),
'group' => array('year')
));

$this->assertEqual($result, $expectation);
}
}
?>

0 comments on commit bbb105f

Please sign in to comment.