Skip to content

Commit

Permalink
[6.x] Fix Builder::withCount() binding error when a scope is added in…
Browse files Browse the repository at this point in the history
…to related model with binding in a sub-select (#30869)

* add failing test case of withCount with 'select' with binding in constraint

* remove 'select' bindings in withCount to prevent binding error if the relation is scoped to add a sub-select with binding
  • Loading branch information
miklcct authored and taylorotwell committed Dec 18, 2019
1 parent ce046df commit 6b8ae3d
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -390,6 +390,7 @@ public function withCount($relations)

if (count($query->columns) > 1) {
$query->columns = [$query->columns[0]];
$query->bindings['select'] = [];
}

// Finally we will add the proper result column alias to the query and run the subselect
Expand Down
13 changes: 13 additions & 0 deletions tests/Database/DatabaseEloquentBuilderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -864,6 +864,19 @@ public function testHasWithConstraintsAndHavingInSubqueryWithCount()
$this->assertEquals(['baz', 'qux', 'quuux'], $builder->getBindings());
}

public function testWithCountAndConstraintsWithBindingInSelectSub()
{
$model = new EloquentBuilderTestModelParentStub;

$builder = $model->newQuery();
$builder->withCount(['foo' => function ($q) use ($model) {
$q->selectSub($model->newQuery()->where('bam', '=', 3)->selectRaw('count(0)'), 'bam_3_count');
}]);

$this->assertSame('select "eloquent_builder_test_model_parent_stubs".*, (select count(*) from "eloquent_builder_test_model_close_related_stubs" where "eloquent_builder_test_model_parent_stubs"."foo_id" = "eloquent_builder_test_model_close_related_stubs"."id") as "foo_count" from "eloquent_builder_test_model_parent_stubs"', $builder->toSql());
$this->assertSame([], $builder->getBindings());
}

public function testHasNestedWithConstraints()
{
$model = new EloquentBuilderTestModelParentStub;
Expand Down

0 comments on commit 6b8ae3d

Please sign in to comment.