From bbb105fc8c1bf125172ff4306ec92355fe6dc620 Mon Sep 17 00:00:00 2001 From: Phally Date: Sat, 9 Jan 2010 20:29:49 +0100 Subject: [PATCH] Added virtual field support for GROUP BY. --- cake/libs/model/datasources/dbo_source.php | 9 ++++++-- .../cases/libs/model/model_read.test.php | 23 +++++++++++++++++++ 2 files changed, 30 insertions(+), 2 deletions(-) mode change 100644 => 100755 cake/libs/model/datasources/dbo_source.php mode change 100644 => 100755 cake/tests/cases/libs/model/model_read.test.php diff --git a/cake/libs/model/datasources/dbo_source.php b/cake/libs/model/datasources/dbo_source.php old mode 100644 new mode 100755 index a0f935e8451..0e559a374af --- a/cake/libs/model/datasources/dbo_source.php +++ b/cake/libs/model/datasources/dbo_source.php @@ -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) )); } @@ -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); diff --git a/cake/tests/cases/libs/model/model_read.test.php b/cake/tests/cases/libs/model/model_read.test.php old mode 100644 new mode 100755 index 3bd57eb05f8..6bc4606f816 --- a/cake/tests/cases/libs/model/model_read.test.php +++ b/cake/tests/cases/libs/model/model_read.test.php @@ -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); } } ?> \ No newline at end of file