Skip to content

Commit 44f37aa

Browse files
authored
Merge pull request #433 from d8vjork/master
Add pivotSynced event listener to flush cache when performing BelongsToMany::sync
2 parents dcc2204 + d036d4a commit 44f37aa

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

src/Traits/ModelCaching.php

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,10 @@ public static function bootCachable()
7575
// $instance->checkCooldownAndFlushAfterPersisting($instance);
7676
// });
7777

78+
static::pivotSynced(function ($instance, $secondInstance, $relationship) {
79+
$instance->checkCooldownAndFlushAfterPersisting($instance, $relationship);
80+
});
81+
7882
static::pivotAttached(function ($instance, $secondInstance, $relationship) {
7983
$instance->checkCooldownAndFlushAfterPersisting($instance, $relationship);
8084
});

tests/Integration/CachedBuilder/BelongsToManyTest.php

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -169,6 +169,49 @@ public function testUncachedRelatedModelDoesntCache()
169169
$this->assertNotNull($uncachedResult);
170170
}
171171

172+
public function testInvalidatingCacheWhenSyncing()
173+
{
174+
$bookId = (new Store)
175+
->disableModelCaching()
176+
->with("books")
177+
->first()
178+
->books
179+
->first()
180+
->id;
181+
$key = sha1("genealabs:laravel-model-caching:testing:{$this->testingSqlitePath}testing.sqlite:stores:genealabslaravelmodelcachingtestsfixturesstore-testing:{$this->testingSqlitePath}testing.sqlite:books-first");
182+
$tags = [
183+
"genealabs:laravel-model-caching:testing:{$this->testingSqlitePath}testing.sqlite:genealabslaravelmodelcachingtestsfixturesstore",
184+
];
185+
186+
$newStores = factory(Store::class, 2)
187+
->create();
188+
189+
$result = Book::find($bookId)
190+
->stores;
191+
192+
Book::find($bookId)
193+
->stores()
194+
->attach($newStores[0]->id);
195+
196+
Book::find($bookId)
197+
->stores()
198+
->sync($newStores->pluck('id'));
199+
200+
$this->assertEmpty(array_diff(
201+
Book::find($bookId)->stores()->pluck((new Store)->getTable() . '.id')->toArray(),
202+
$newStores->pluck('id')->toArray()
203+
));
204+
205+
$cachedResult = $this
206+
->cache()
207+
->tags($tags)
208+
->get($key)['value']
209+
?? null;
210+
211+
$this->assertNotEmpty($result);
212+
$this->assertNull($cachedResult);
213+
}
214+
172215
// /** @group test */
173216
// public function testUncachedDetachesFromCached()
174217
// {

0 commit comments

Comments
 (0)