diff --git a/framework/CHANGELOG.md b/framework/CHANGELOG.md index 600a3420746..1d82419f857 100644 --- a/framework/CHANGELOG.md +++ b/framework/CHANGELOG.md @@ -19,6 +19,7 @@ Yii Framework 2 Change Log - Enh #20279: Add to the `\yii\web\Request` `csrfHeader` property to configure a custom HTTP header for CSRF validation (olegbaturin) - Enh #20279: Add to the `\yii\web\Request` `csrfTokenSafeMethods` property to configure a custom safe HTTP methods list (olegbaturin) - Bug #20140: Fix compatibility with PHP 8.4: calling `session_set_save_handler()` (Izumi-kun) +- Enh #20277: Eager loading in `\yii\db\ActiveRecord::refresh` (chriscpty) 2.0.51 July 18, 2024 -------------------- diff --git a/framework/db/ActiveRecord.php b/framework/db/ActiveRecord.php index 130285617ed..f699994d9d3 100644 --- a/framework/db/ActiveRecord.php +++ b/framework/db/ActiveRecord.php @@ -280,8 +280,10 @@ protected static function filterValidColumnNames($db, array $aliases) /** * {@inheritdoc} + * + * @param array $with If set, reloads the given relations. */ - public function refresh() + public function refresh(array $with = []) { $query = static::find(); $tableName = key($query->getTablesUsedInFrom()); @@ -290,7 +292,8 @@ public function refresh() foreach ($this->getPrimaryKey(true) as $key => $value) { $pk[$tableName . '.' . $key] = $value; } - $query->where($pk); + $query->where($pk) + ->with(...$with); /* @var $record BaseActiveRecord */ $record = $query->noCache()->one(); diff --git a/framework/db/BaseActiveRecord.php b/framework/db/BaseActiveRecord.php index 761bc2cb994..fc941628840 100644 --- a/framework/db/BaseActiveRecord.php +++ b/framework/db/BaseActiveRecord.php @@ -1082,8 +1082,8 @@ protected function refreshInternal($record) $this->_attributes[$name] = isset($record->_attributes[$name]) ? $record->_attributes[$name] : null; } $this->_oldAttributes = $record->_oldAttributes; - $this->_related = []; - $this->_relationsDependencies = []; + $this->_related = $record->_related; + $this->_relationsDependencies = $record->_relationsDependencies; $this->afterRefresh(); return true; diff --git a/tests/framework/ar/ActiveRecordTestTrait.php b/tests/framework/ar/ActiveRecordTestTrait.php index 3bb161f7f8f..fc0b8ef83c8 100644 --- a/tests/framework/ar/ActiveRecordTestTrait.php +++ b/tests/framework/ar/ActiveRecordTestTrait.php @@ -288,6 +288,10 @@ public function testRefresh() $customer->name = 'to be refreshed'; $this->assertTrue($customer->refresh()); $this->assertEquals('user1', $customer->name); + $this->assertFalse($customer->isRelationPopulated('profile')); + + $this->assertTrue($customer->refresh(['profile'])); + $this->assertTrue($customer->isRelationPopulated('profile')); } public function testEquals()