From 2b26ede80562b90a0ec6e7c7cafb356691f537d3 Mon Sep 17 00:00:00 2001 From: Moritz Heinemann Date: Sun, 18 Dec 2016 16:57:20 +0100 Subject: [PATCH] fix withCount aliasing problem --- src/Illuminate/Database/Eloquent/Builder.php | 4 ++++ tests/Database/DatabaseEloquentBuilderTest.php | 9 +++++++++ 2 files changed, 13 insertions(+) diff --git a/src/Illuminate/Database/Eloquent/Builder.php b/src/Illuminate/Database/Eloquent/Builder.php index c3df1fa5208f..b19ca7bc9712 100755 --- a/src/Illuminate/Database/Eloquent/Builder.php +++ b/src/Illuminate/Database/Eloquent/Builder.php @@ -1089,6 +1089,10 @@ public function withCount($relations) // the resulting column. This allows multiple counts on the same relationship name. $segments = explode(' ', $name); + // We want to forget the alias in the case the last loop set an alias, but the current + // loop does not set a new alias. + unset($alias); + if (count($segments) == 3 && Str::lower($segments[1]) == 'as') { list($name, $alias) = [$segments[0], $segments[2]]; } diff --git a/tests/Database/DatabaseEloquentBuilderTest.php b/tests/Database/DatabaseEloquentBuilderTest.php index 51ed426ea13a..3b027def5a53 100755 --- a/tests/Database/DatabaseEloquentBuilderTest.php +++ b/tests/Database/DatabaseEloquentBuilderTest.php @@ -633,6 +633,15 @@ public function testWithCountAndRename() $this->assertEquals('select *, (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_bar_count" from "eloquent_builder_test_model_parent_stubs"', $builder->toSql()); } + public function testWithCountMultipleAndPartialRename() + { + $model = new EloquentBuilderTestModelParentStub; + + $builder = $model->withCount(['foo as foo_bar', 'foo']); + + $this->assertEquals('select *, (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_bar_count", (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()); + } + public function testHasWithContraintsAndHavingInSubquery() { $model = new EloquentBuilderTestModelParentStub;