From b59d5050d7cb94b1a66dc11cf72c20cb198a195a Mon Sep 17 00:00:00 2001 From: Arif Hoque Date: Fri, 24 Jul 2026 21:39:30 +0600 Subject: [PATCH] Add model relation cache forget and reload helpers --- src/Phaseolies/Database/Entity/Model.php | 26 +++++++++++++++++++ .../Query/EntityRelationshipBehavior.php | 16 ++++++++++++ 2 files changed, 42 insertions(+) diff --git a/src/Phaseolies/Database/Entity/Model.php b/src/Phaseolies/Database/Entity/Model.php index afa2c723..375b57cb 100644 --- a/src/Phaseolies/Database/Entity/Model.php +++ b/src/Phaseolies/Database/Entity/Model.php @@ -974,6 +974,32 @@ public function getRelation(string $relation) return $this->relations[$relation] ?? null; } + /** + * Forget a loaded relationship so it will be queried again on next access. + * + * @param string $relation + * @return $this + */ + public function forget(string $relation): self + { + unset($this->relations[$relation]); + + return $this; + } + + /** + * Reload a relationship from the database. + * + * @param string $relation + * @return mixed + */ + public function reload(string $relation) + { + $this->forget($relation); + + return $this->{$relation}; + } + /** * Magic getter for accessing model attributes and relationships * diff --git a/tests/Model/Query/EntityRelationshipBehavior.php b/tests/Model/Query/EntityRelationshipBehavior.php index 4ea80eed..ebddd40a 100644 --- a/tests/Model/Query/EntityRelationshipBehavior.php +++ b/tests/Model/Query/EntityRelationshipBehavior.php @@ -926,6 +926,22 @@ public function testRelateIsIdempotentForSameSet(): void $this->assertEquals([], $changes['detached']); } + /** + * Refreshing a loaded relation exposes pivot changes on the same model. + */ + public function testRefreshRelationClearsStaleRelationCache(): void + { + $post = MockPost::find(1); + + $this->assertEquals([1, 2], $post->tags->pluck('id')->sort()->values()->toArray()); + + $post->tags()->relate([1, 4]); + + $this->assertEquals([1, 2], $post->tags->pluck('id')->sort()->values()->toArray()); + $this->assertEquals([1, 4], $post->reload('tags')->pluck('id')->sort()->values()->toArray()); + $this->assertEquals([1, 4], $post->tags->pluck('id')->sort()->values()->toArray()); + } + // ========================================================================= // 16. MIXED omit + embed // =========================================================================