From 9243333a12cd93bc00430e5244ce9287c6962a88 Mon Sep 17 00:00:00 2001 From: rexfinlayson Date: Thu, 2 Jul 2020 12:20:48 +1200 Subject: [PATCH] Add some code to stop scopes from being applied twice. Also added a test for this as well. --- src/Traits/Buildable.php | 15 +++++++++++++++ tests/Integration/CachedBuilder/ScopeTest.php | 14 ++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/src/Traits/Buildable.php b/src/Traits/Buildable.php index 235cbc7..82cacf7 100644 --- a/src/Traits/Buildable.php +++ b/src/Traits/Buildable.php @@ -292,4 +292,19 @@ function () use ($arguments, $cacheKey, $method) { } ); } + + /** + * Apply the scopes if they haven't already been applied, if they have + * just return the builder. This prevents scopes from being applied twice. + * + * @return static + */ + public function applyScopes() + { + if ($this->scopesAreApplied) { + return $this; + } + + return parent::applyScopes(); + } } diff --git a/tests/Integration/CachedBuilder/ScopeTest.php b/tests/Integration/CachedBuilder/ScopeTest.php index 6da7c24..1db5445 100644 --- a/tests/Integration/CachedBuilder/ScopeTest.php +++ b/tests/Integration/CachedBuilder/ScopeTest.php @@ -8,6 +8,7 @@ use GeneaLabs\LaravelModelCaching\Tests\Fixtures\UncachedAuthorWithInlineGlobalScope; use GeneaLabs\LaravelModelCaching\Tests\Fixtures\User; use Illuminate\Database\Eloquent\Relations\HasMany; +use Illuminate\Support\Facades\DB; use Illuminate\Support\Str; class ScopeTest extends IntegrationTestCase @@ -174,4 +175,17 @@ public function testLocalScopesInRelationship() // $this->assertNotEquals($authors1, $authors2); $this->markTestSkipped(); } + + public function testScopeNotAppliedTwice() + { + factory(Author::class, 10)->create(); + $user = factory(User::class)->create(["name" => "Anton Junior"]); + $this->actingAs($user); + DB::enableQueryLog(); + $authorsA = (new AuthorBeginsWithScoped) + ->get(); + $queryLog = DB::getQueryLog(); + $this->assertCount(1, $queryLog); + $this->assertCount(1, $queryLog[0]['bindings'], "There should only be 1 binding, scope is being applied more than once."); + } }