Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Count cache support nullable #118

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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);
}
}
Loading