Skip to content

Commit

Permalink
Fix issue when creating models without related behaviours models
Browse files Browse the repository at this point in the history
  • Loading branch information
fmarquesto committed Jun 18, 2024
1 parent 1f36839 commit 30cef44
Show file tree
Hide file tree
Showing 4 changed files with 17 additions and 3 deletions.
2 changes: 1 addition & 1 deletion src/Behaviours/CacheConfig.php
Original file line number Diff line number Diff line change
Expand Up @@ -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};
}
Expand Down
6 changes: 5 additions & 1 deletion src/Behaviours/Cacheable.php
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}
Expand Down
4 changes: 3 additions & 1 deletion src/Behaviours/ValueCache/ValueCache.php
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
8 changes: 8 additions & 0 deletions tests/Acceptance/CountCacheTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}

0 comments on commit 30cef44

Please sign in to comment.