Skip to content

Commit

Permalink
fix withCount aliasing problem
Browse files Browse the repository at this point in the history
  • Loading branch information
moritz-h committed Dec 18, 2016
1 parent 359b7c3 commit 2b26ede
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/Illuminate/Database/Eloquent/Builder.php
Original file line number Diff line number Diff line change
Expand Up @@ -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]];
}
Expand Down
9 changes: 9 additions & 0 deletions tests/Database/DatabaseEloquentBuilderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down

0 comments on commit 2b26ede

Please sign in to comment.