diff --git a/src/Behaviours/CacheConfig.php b/src/Behaviours/CacheConfig.php index e84c2eb..30a4e74 100644 --- a/src/Behaviours/CacheConfig.php +++ b/src/Behaviours/CacheConfig.php @@ -23,7 +23,7 @@ public function relation(Model $model): Relation /** * Returns the current related model. */ - public function relatedModel(Model $model): Model + public function relatedModel(Model $model): ?Model { return $model->{$this->relationName}; } diff --git a/src/Behaviours/Cacheable.php b/src/Behaviours/Cacheable.php index a2855df..1c34c6f 100644 --- a/src/Behaviours/Cacheable.php +++ b/src/Behaviours/Cacheable.php @@ -109,8 +109,12 @@ public function rebuildCacheRecord(CacheConfig $config, Model $model, $command): /** * Update the cache value for the model. */ - protected function updateCacheValue(Model $model, CacheConfig $config, $value): void + protected function updateCacheValue(?Model $model, CacheConfig $config, $value): void { + if(!$model){ + return; + } + $model->{$config->aggregateField} = $model->{$config->aggregateField} + $value; $model->save(); } diff --git a/src/Behaviours/ValueCache/ValueCache.php b/src/Behaviours/ValueCache/ValueCache.php index ecf11f0..53251a7 100644 --- a/src/Behaviours/ValueCache/ValueCache.php +++ b/src/Behaviours/ValueCache/ValueCache.php @@ -39,7 +39,9 @@ public function updateRelated(bool $new): void return; } - $relatedModel = $config->emptyRelatedModel($this->model)->find($this->model->$foreignKey); + if(!$relatedModel = $config->emptyRelatedModel($this->model)->find($this->model->$foreignKey)){ + return; + } $relatedModel->{$config->aggregateField} = $this->model->{$config->sourceField}; $relatedModel->save(); diff --git a/tests/Acceptance/CountCacheTest.php b/tests/Acceptance/CountCacheTest.php index b3a9d63..d1aff05 100644 --- a/tests/Acceptance/CountCacheTest.php +++ b/tests/Acceptance/CountCacheTest.php @@ -57,4 +57,12 @@ public function test_cacheIsNotUsedWhenRelatedFieldIsNull() $this->assertEquals(1, $user1->fresh()->postCount); } + + public function test_canCreateModelWithoutRelatedBehavioursModels() + { + $post = new Post(); + $post->save(); + + $this->assertModelExists($post); + } } \ No newline at end of file