Skip to content

Commit

Permalink
Merge pull request #118 from fmarquesto/count-cache-support-nullable
Browse files Browse the repository at this point in the history
Count cache support nullable
  • Loading branch information
kirkbushell authored May 16, 2024
2 parents 3c20baf + 1af0c02 commit d4734d7
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
6 changes: 5 additions & 1 deletion src/Behaviours/CountCache/CountCache.php
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,11 @@ public function update(): void
$originalRelatedModel = $config->emptyRelatedModel($this->model)->find($this->model->getOriginal($foreignKey));

$this->updateCacheValue($originalRelatedModel, $config, -1);
$this->updateCacheValue($config->relatedModel($this->model), $config, 1);

// if the relation is null, then we don't need to do anything else.
if($this->model->{$foreignKey}) {
$this->updateCacheValue($config->relatedModel($this->model), $config, 1);
}
});
}

Expand Down
14 changes: 14 additions & 0 deletions tests/Acceptance/CountCacheTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,4 +43,18 @@ public function testItCanHandleModelRestoration()

$this->assertEquals(1, $post->fresh()->commentCount);
}

public function testItCanHandleNullableRelation()
{
$user1 = User::factory()->create();
$posts = Post::factory()->count(2)->for($user1)->create();

$this->assertEquals(2, $user1->fresh()->postCount);

$firstPost = $posts->first()->fresh();
$firstPost->userId = null;
$firstPost->save();

$this->assertEquals(1, $user1->fresh()->postCount);
}
}

0 comments on commit d4734d7

Please sign in to comment.