Skip to content

Add some code to stop scopes from being applied twice. #358

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

Merged
merged 1 commit into from
Jul 2, 2020
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
15 changes: 15 additions & 0 deletions src/Traits/Buildable.php
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Copy link
Owner

@mikebronner mikebronner Jul 2, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@saernz Quick question: where is $this->scopesAreApplied defined or updated when scopes are applied? I couldn't find it when doing a global search.

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh, nevermind, I found it in Caching.php ... sorry, overlooked that earlier.

return $this;
}

return parent::applyScopes();
}
}
14 changes: 14 additions & 0 deletions tests/Integration/CachedBuilder/ScopeTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.");
}
}