diff --git a/lib/Doctrine/Record.php b/lib/Doctrine/Record.php index 338317364..7d17d2352 100644 --- a/lib/Doctrine/Record.php +++ b/lib/Doctrine/Record.php @@ -649,11 +649,14 @@ abstract class Doctrine_Record extends Doctrine_Record_Abstract implements Count * refresh * refresh internal data from the database * + * @param bool $deep If true, fetch also current relations. Caution: this deletes + * any aggregated values you may have queried beforee + * * @throws Doctrine_Record_Exception When the refresh operation fails (when the database row * this record represents does not exist anymore) * @return boolean */ - public function refresh() + public function refresh($deep = false) { $id = $this->identifier(); if ( ! is_array($id)) { @@ -664,15 +667,25 @@ abstract class Doctrine_Record extends Doctrine_Record_Abstract implements Count } $id = array_values($id); - // Use FETCH_ARRAY to avoid clearing object relations - $record = $this->getTable()->find($id, Doctrine::FETCH_ARRAY); + if ($deep) { + $query = $this->getTable()->createQuery(); + foreach (array_keys($this->_references) as $name) { + $query->leftJoin(get_class($this) . '.' . $name); + } + $query->where(implode(' = ? AND ', $this->getTable()->getIdentifierColumnNames()) . ' = ?'); + $record = $query->fetchOne($id); + } else { + // Use FETCH_ARRAY to avoid clearing object relations + $record = $this->getTable()->find($id, Doctrine::HYDRATE_ARRAY); + if ($record) { + $this->hydrate($record); + } + } if ($record === false) { throw new Doctrine_Record_Exception('Failed to refresh. Record does not exist.'); } - $this->hydrate($record); - $this->_modified = array(); $this->prepareIdentifiers(); diff --git a/tests/RecordTestCase.php b/tests/RecordTestCase.php index bcaa4b055..c41c09c4f 100644 --- a/tests/RecordTestCase.php +++ b/tests/RecordTestCase.php @@ -868,4 +868,29 @@ class Doctrine_Record_TestCase extends Doctrine_UnitTestCase $this->assertEqual(count($user->Address), 0); } + public function testRefreshDeep() + { + $user = $this->connection->getTable("User")->find(4); + $user->Address[0]->address = "Address #1"; + $user->Address[1]->address = "Address #2"; + $user->save(); + $this->assertEqual(count($user->Address), 2); + + Doctrine_Query::create()->delete()->from('EntityAddress')->where('user_id = ? AND address_id = ?', array($user->id, $user->Address[1]->id))->execute(); + $user->refresh(true); + $this->assertEqual(count($user->Address), 1); + + $address = $user->Address[0]; + Doctrine_Query::create()->delete()->from('EntityAddress')->where('user_id = ? AND address_id = ?', array($user->id, $user->Address[0]->id))->execute(); + $user->refresh(true); + $this->assertEqual(count($user->Address), 0); + + $entity_address = new EntityAddress(); + $entity_address->user_id = $user->id; + $entity_address->address_id = $address->id; + $entity_address->save(); + $this->assertNotEqual(count($user->Address), 1); + $user->refresh(true); + $this->assertEqual(count($user->Address), 1); + } }