diff --git a/src/Illuminate/Database/Eloquent/Builder.php b/src/Illuminate/Database/Eloquent/Builder.php index 495d00a4eff1..c56f3845e78f 100755 --- a/src/Illuminate/Database/Eloquent/Builder.php +++ b/src/Illuminate/Database/Eloquent/Builder.php @@ -1056,6 +1056,15 @@ public function withCount($relations) $relations = is_array($relations) ? $relations : func_get_args(); foreach ($this->parseWithRelations($relations) as $name => $constraints) { + // If relation string matches "relation as newname" extract first part as the relation + // name and remember the last part as output name. + $nameParts = explode(' ', $name); + $resultName = ''; + if (count($nameParts) == 3 && Str::lower($nameParts[1]) == 'as') { + $name = $nameParts[0]; + $resultName = $nameParts[2]; + } + // Here we will get the relationship count query and prepare to add it to the main query // as a sub-select. First, we'll get the "has" query and use that to get the relation // count query. We will normalize the relation name then append _count as the name. @@ -1069,7 +1078,7 @@ public function withCount($relations) $query->mergeModelDefinedRelationConstraints($relation->getQuery()); - $this->selectSub($query->toBase(), snake_case($name).'_count'); + $this->selectSub($query->toBase(), snake_case(! empty($resultName) ? $resultName : $name).'_count'); } return $this; diff --git a/tests/Database/DatabaseEloquentBuilderTest.php b/tests/Database/DatabaseEloquentBuilderTest.php index 67dc4d1fe4d7..d8bda3a14eec 100755 --- a/tests/Database/DatabaseEloquentBuilderTest.php +++ b/tests/Database/DatabaseEloquentBuilderTest.php @@ -554,6 +554,15 @@ public function testWithCountAndContraintsAndHaving() $this->assertEquals(['qux', 'baz', 1], $builder->getBindings()); } + public function testWithCountAndRename() + { + $model = new EloquentBuilderTestModelParentStub; + + $builder = $model->withCount('foo as foo_bar'); + + $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 testHasWithContraintsAndHavingInSubquery() { $model = new EloquentBuilderTestModelParentStub;