diff --git a/extensions/mongodb/ActiveRecord.php b/extensions/mongodb/ActiveRecord.php index 3fd3bad485..83fda1a125 100644 --- a/extensions/mongodb/ActiveRecord.php +++ b/extensions/mongodb/ActiveRecord.php @@ -222,7 +222,9 @@ abstract class ActiveRecord extends BaseActiveRecord if (empty($values)) { $currentAttributes = $this->getAttributes(); foreach ($this->primaryKey() as $key) { - $values[$key] = isset($currentAttributes[$key]) ? $currentAttributes[$key] : null; + if (isset($currentAttributes[$key])) { + $values[$key] = $currentAttributes[$key]; + } } } $newId = static::getCollection()->insert($values); diff --git a/extensions/mongodb/CHANGELOG.md b/extensions/mongodb/CHANGELOG.md index 69936302cb..86c48461c7 100644 --- a/extensions/mongodb/CHANGELOG.md +++ b/extensions/mongodb/CHANGELOG.md @@ -4,6 +4,7 @@ Yii Framework 2 mongodb extension Change Log 2.0.1 under development ----------------------- +- Bug #6026: Fixed `yii\mongodb\ActiveRecord` saves `null` as `_id`, if attributes are empty (klimov-paul) - Enh #3855: Added debug toolbar panel for MongoDB (klimov-paul) - Enh #5592: Added support for 'findAndModify' operation at `yii\mongodb\Query` and `yii\mongodb\ActiveQuery` (klimov-paul) diff --git a/tests/unit/extensions/mongodb/ActiveRecordTest.php b/tests/unit/extensions/mongodb/ActiveRecordTest.php index b89fdac4d9..177f5b17b2 100644 --- a/tests/unit/extensions/mongodb/ActiveRecordTest.php +++ b/tests/unit/extensions/mongodb/ActiveRecordTest.php @@ -275,4 +275,18 @@ class ActiveRecordTest extends MongoDbTestCase $this->assertTrue($customer instanceof Customer); $this->assertEquals($newName, $customer->name); } + + /** + * @depends testInsert + * + * @see https://github.com/yiisoft/yii2/issues/6026 + */ + public function testInsertEmptyAttributes() + { + $record = new Customer(); + $record->save(false); + + $this->assertTrue($record->_id instanceof \MongoId); + $this->assertFalse($record->isNewRecord); + } }