From 6b8ae3d71617da38f881321676ddcb6506227488 Mon Sep 17 00:00:00 2001 From: Michael Tsang Date: Wed, 18 Dec 2019 23:23:29 +0800 Subject: [PATCH] [6.x] Fix Builder::withCount() binding error when a scope is added into 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 --- .../Eloquent/Concerns/QueriesRelationships.php | 1 + tests/Database/DatabaseEloquentBuilderTest.php | 13 +++++++++++++ 2 files changed, 14 insertions(+) diff --git a/src/Illuminate/Database/Eloquent/Concerns/QueriesRelationships.php b/src/Illuminate/Database/Eloquent/Concerns/QueriesRelationships.php index 635d3d0817a0..0916b99ebe3b 100644 --- a/src/Illuminate/Database/Eloquent/Concerns/QueriesRelationships.php +++ b/src/Illuminate/Database/Eloquent/Concerns/QueriesRelationships.php @@ -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 diff --git a/tests/Database/DatabaseEloquentBuilderTest.php b/tests/Database/DatabaseEloquentBuilderTest.php index 802424a66d44..d772a8477a30 100755 --- a/tests/Database/DatabaseEloquentBuilderTest.php +++ b/tests/Database/DatabaseEloquentBuilderTest.php @@ -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;