From 56740402e11bc214011441fa53131b5497f450b8 Mon Sep 17 00:00:00 2001 From: Ruben Robles Date: Wed, 20 Jul 2022 16:40:03 +0200 Subject: [PATCH 1/2] Add pivotSynced event listener to flush cache --- src/Traits/ModelCaching.php | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/Traits/ModelCaching.php b/src/Traits/ModelCaching.php index 587f8146..5b240b4f 100644 --- a/src/Traits/ModelCaching.php +++ b/src/Traits/ModelCaching.php @@ -75,6 +75,10 @@ public static function bootCachable() // $instance->checkCooldownAndFlushAfterPersisting($instance); // }); + static::pivotSynced(function ($instance, $secondInstance, $relationship) { + $instance->checkCooldownAndFlushAfterPersisting($instance, $relationship); + }); + static::pivotAttached(function ($instance, $secondInstance, $relationship) { $instance->checkCooldownAndFlushAfterPersisting($instance, $relationship); }); From d036d4a86fae112eaa240537575b7d55e465e89b Mon Sep 17 00:00:00 2001 From: Ruben Robles Date: Wed, 20 Jul 2022 19:14:58 +0200 Subject: [PATCH 2/2] Add test for pivotSync --- .../CachedBuilder/BelongsToManyTest.php | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/tests/Integration/CachedBuilder/BelongsToManyTest.php b/tests/Integration/CachedBuilder/BelongsToManyTest.php index 744d7566..1fb8d212 100644 --- a/tests/Integration/CachedBuilder/BelongsToManyTest.php +++ b/tests/Integration/CachedBuilder/BelongsToManyTest.php @@ -169,6 +169,49 @@ public function testUncachedRelatedModelDoesntCache() $this->assertNotNull($uncachedResult); } + public function testInvalidatingCacheWhenSyncing() + { + $bookId = (new Store) + ->disableModelCaching() + ->with("books") + ->first() + ->books + ->first() + ->id; + $key = sha1("genealabs:laravel-model-caching:testing:{$this->testingSqlitePath}testing.sqlite:stores:genealabslaravelmodelcachingtestsfixturesstore-testing:{$this->testingSqlitePath}testing.sqlite:books-first"); + $tags = [ + "genealabs:laravel-model-caching:testing:{$this->testingSqlitePath}testing.sqlite:genealabslaravelmodelcachingtestsfixturesstore", + ]; + + $newStores = factory(Store::class, 2) + ->create(); + + $result = Book::find($bookId) + ->stores; + + Book::find($bookId) + ->stores() + ->attach($newStores[0]->id); + + Book::find($bookId) + ->stores() + ->sync($newStores->pluck('id')); + + $this->assertEmpty(array_diff( + Book::find($bookId)->stores()->pluck((new Store)->getTable() . '.id')->toArray(), + $newStores->pluck('id')->toArray() + )); + + $cachedResult = $this + ->cache() + ->tags($tags) + ->get($key)['value'] + ?? null; + + $this->assertNotEmpty($result); + $this->assertNull($cachedResult); + } + // /** @group test */ // public function testUncachedDetachesFromCached() // {