Skip to content
Browse files

Initial implementation of model virtual fields

  • Loading branch information...
1 parent 285329e commit 53765312df8c2a38cd52a90430dfb2675cada392 @lorenzo lorenzo committed
Showing with 53 additions and 3 deletions.
  1. +37 −3 cake/libs/model/datasources/dbo_source.php
  2. +16 −0 cake/tests/cases/libs/model/model_read.test.php
View
40 cake/libs/model/datasources/dbo_source.php
@@ -369,6 +369,7 @@ function fetchAll($sql, $cache = true, $modelName = null) {
$first = $this->fetchRow();
if ($first != null) {
+ $this->fetchVirtualField($first);
$out[] = $first;
}
while ($this->hasResult() && $item = $this->fetchResult()) {
@@ -390,6 +391,29 @@ function fetchAll($sql, $cache = true, $modelName = null) {
}
}
+ function fetchVirtualField(&$result) {
+ if (isset($result[0]) && is_array($result[0])) {
+ foreach ($result[0] as $field => $value) {
+ if (strpos($field,'__') === false) {
+ continue;
+ }
+ list($alias,$virtual) = explode('__',$field);
+
+ if (!ClassRegistry::isKeySet($alias)) {
+ retrun;
+ }
+ $model = ClassRegistry::getObject($alias);
+ if (isset($model->virtualFields[$virtual])) {
+ $result[$alias][$virtual] = $value;
+ unset($result[0][$field]);
+ }
+ }
+ if (empty($result[0])) {
+ unset($result[0]);
+ }
+ }
+ }
+
/**
* Modifies $result array to place virtual fields in model entry where they belongs to
*
@@ -1765,6 +1789,14 @@ function __scrubQueryData($data) {
return $data;
}
+ function _constructVirtualFields(&$model,$fields) {
+ $virtual = array();
+ foreach ($fields as $name => $expression) {
+ $virtual[] = $expression . " {$this->alias} {$model->alias}__{$name}";
+ }
+ return $virtual;
+ }
+
/**
* Converts model virtual fields into sql expressions to be fetched later
*
@@ -1873,9 +1905,11 @@ function fields(&$model, $alias = null, $fields = array(), $quote = true) {
}
}
}
-
- if (!empty($virtual)) {
- $fields = array_merge($fields,$this->_constructVirtualFields($model,$alias,$virtual));
+ if (!empty($model->virtualFields)) {
+ if ($allFields) {
+ $fields = array_merge($fields,$this->_constructVirtualFields($model,$model->virtualFields));
+ } else {
+ }
}
return array_unique($fields);
}
View
16 cake/tests/cases/libs/model/model_read.test.php
@@ -26,6 +26,22 @@
*/
class ModelReadTest extends BaseModelTest {
+ function testVirtualFields() {
+ $this->loadFixtures('Post');
+ $Post = ClassRegistry::init('Post');
+ $Post->virtualFields = array('two' => "1 + 1");
+ $expected = array(
+ 'author_id' => 1,
+ 'title' => 'First Post',
+ 'body' => 'First Post Body',
+ 'published' => 'Y',
+ 'created' => '2007-03-18 10:39:23',
+ 'updated' => '2007-03-18 10:41:31'
+ );
+ debug($Post->find('first'));
+ exit;
+ }
+
/**
* testVirtualFields()
*

0 comments on commit 5376531

Please sign in to comment.
Something went wrong with that request. Please try again.