diff --git a/framework/CHANGELOG.md b/framework/CHANGELOG.md index 2cbf31603a..ae03004f51 100644 --- a/framework/CHANGELOG.md +++ b/framework/CHANGELOG.md @@ -28,6 +28,7 @@ Yii Framework 2 Change Log - Bug #18909: Fix bug with binding default action parameters for controllers (bizley) - Bug #18955: Check `yiisoft/yii2-swiftmailer` before using as default mailer in `yii\base\Application` (WinterSilence) - Bug #18988: Fix default value of `yii\console\controllers\MessageController::$translator` (WinterSilence) +- Bug #18993: Load defaults by `attributes()` in `yii\db\ActiveRecord::loadDefaultValues()` (WinterSilence) 2.0.43 August 09, 2021 diff --git a/framework/db/ActiveRecord.php b/framework/db/ActiveRecord.php index 0ccbcca630..bfd33b16d2 100644 --- a/framework/db/ActiveRecord.php +++ b/framework/db/ActiveRecord.php @@ -115,9 +115,13 @@ class ActiveRecord extends BaseActiveRecord */ public function loadDefaultValues($skipIfSet = true) { - foreach (static::getTableSchema()->columns as $column) { - if ($column->defaultValue !== null && (!$skipIfSet || $this->{$column->name} === null)) { - $this->{$column->name} = $column->defaultValue; + $columns = static::getTableSchema()->columns; + foreach ($this->attributes() as $name) { + if (isset($columns[$name])) { + $defaultValue = $columns[$name]->defaultValue; + if ($defaultValue !== null && (!$skipIfSet || $this->getAttribute($name) === null)) { + $this->setAttribute($name, $defaultValue); + } } } diff --git a/tests/data/ar/CroppedType.php b/tests/data/ar/CroppedType.php new file mode 100644 index 0000000000..92922a7e1f --- /dev/null +++ b/tests/data/ar/CroppedType.php @@ -0,0 +1,33 @@ +assertEquals(1.23, $model->float_col2); $this->assertEquals(33.22, $model->numeric_col); $this->assertEquals(true, $model->bool_col2); - if ($this instanceof CubridActiveRecordTest) { // cubrid has non-standard timestamp representation $this->assertEquals('12:00:00 AM 01/01/2002', $model->time); @@ -1354,15 +1354,18 @@ abstract class ActiveRecordTest extends DatabaseTestCase $model = new Type(); $model->char_col2 = 'not something'; - $model->loadDefaultValues(); $this->assertEquals('not something', $model->char_col2); $model = new Type(); $model->char_col2 = 'not something'; - $model->loadDefaultValues(false); $this->assertEquals('something', $model->char_col2); + + // Cropped model with 2 attributes/columns + $model = new CroppedType(); + $model->loadDefaultValues(); + $this->assertEquals(['int_col2' => 1], $model->toArray()); } public function testUnlinkAllViaTable()