Skip to content
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

[10.x] Fixes on nesting operations performed while applying scopes. #50207

Merged
merged 2 commits into from
Feb 25, 2024
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
4 changes: 2 additions & 2 deletions src/Illuminate/Database/Eloquent/Builder.php
Original file line number Diff line number Diff line change
Expand Up @@ -1454,9 +1454,9 @@ protected function groupWhereSliceForScope(QueryBuilder $query, $whereSlice)
// Here we'll check if the given subset of where clauses contains any "or"
// booleans and in this case create a nested where expression. That way
// we don't add any unnecessary nesting thus keeping the query clean.
if ($whereBooleans->contains('or')) {
if ($whereBooleans->contains(fn ($logicalOperator) => str_contains($logicalOperator, 'or'))) {
$query->wheres[] = $this->createNestedWhere(
$whereSlice, $whereBooleans->first()
$whereSlice, str_replace(' not', '', $whereBooleans->first())
);
} else {
$query->wheres = array_merge($query->wheres, $whereSlice);
Expand Down
26 changes: 26 additions & 0 deletions tests/Database/DatabaseEloquentLocalScopesTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,32 @@ public function testLocalScopesCanChained()
$this->assertSame('select * from "table" where "active" = ? and "type" = ?', $query->toSql());
$this->assertEquals([true, 'foo'], $query->getBindings());
}

public function testLocalScopeNestingDoesntDoubleFirstWhereClauseNegation()
{
$model = new EloquentLocalScopesTestModel;
$query = $model
->newQuery()
->whereNot('firstWhere', true)
->orWhere('secondWhere', true)
->active();

$this->assertSame('select * from "table" where (not "firstWhere" = ? or "secondWhere" = ?) and "active" = ?', $query->toSql());
$this->assertEquals([true, true, true], $query->getBindings());
}

public function testLocalScopeNestingGroupsOrNotWhereClause()
{
$model = new EloquentLocalScopesTestModel;
$query = $model
->newQuery()
->where('firstWhere', true)
->orWhereNot('secondWhere', true)
->active();

$this->assertSame('select * from "table" where ("firstWhere" = ? or not "secondWhere" = ?) and "active" = ?', $query->toSql());
$this->assertEquals([true, true, true], $query->getBindings());
}
}

class EloquentLocalScopesTestModel extends Model
Expand Down
Loading