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

[5.3] Rename option for withCount() #15279

Merged
merged 3 commits into from
Sep 6, 2016
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
11 changes: 10 additions & 1 deletion src/Illuminate/Database/Eloquent/Builder.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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;
Expand Down
9 changes: 9 additions & 0 deletions tests/Database/DatabaseEloquentBuilderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down