diff --git a/src/GenericModel.php b/src/GenericModel.php index 5ab3c95..bebcc52 100644 --- a/src/GenericModel.php +++ b/src/GenericModel.php @@ -625,15 +625,16 @@ public function reload(): static /** * Save the model changes * + * @param bool $saveToRegistry save the model to the registry (if enabled) * @return bool */ - public function save(): bool + public function save(bool $saveToRegistry = true): bool { // new model, generate id and save in registry if (!$this->getId()) { $this->generateId(); - if (static::$registry) { + if (static::$registry && $saveToRegistry) { ModelRegistry::getInstance()->save($this); } } diff --git a/test/tests/TestDriverTest.php b/test/tests/TestDriverTest.php index 1c8f034..d34dbfc 100644 --- a/test/tests/TestDriverTest.php +++ b/test/tests/TestDriverTest.php @@ -755,6 +755,25 @@ public function testGetWithRegistry(): void $this->assertSame($item2, ModelRegistry::getInstance()->get(TestModel::class, $id)); } + public function testSaveWithRegistry(): void + { + $item = new TestModel(); + $this->assertNull($item->getId()); + + $item->save(false); + $this->assertNull(ModelRegistry::getInstance()->get(TestModel::class, $item->id)); + + // Models are only added to the registry when they are saved for the first time + $item->save(); + $this->assertNull(ModelRegistry::getInstance()->get(TestModel::class, $item->id)); + + // Reset id to create a new model + $item->setId(null); + + $item->save(); + $this->assertSame($item, ModelRegistry::getInstance()->get(TestModel::class, $item->id)); + } + protected function tearDown(): void { TestModel::clearTestEntries();