Skip to content

Commit

Permalink
Fix bug related to sub select queries and extra select statements.
Browse files Browse the repository at this point in the history
The sub select query must have only one selected column otherwise sql
will throw an error.

If a sub select function (e.g. withCount) is called with a model that
has select queries as a global scope this will cause the error.
  • Loading branch information
ChrisAtUdemy committed Apr 30, 2017
1 parent f7e9f74 commit 432816b
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/Illuminate/Database/Query/Builder.php
Original file line number Diff line number Diff line change
Expand Up @@ -279,6 +279,7 @@ public function selectSub($query, $as)
protected function parseSubSelect($query)
{
if ($query instanceof self) {
$query->columns = [$query->columns[0]];
return [$query->toSql(), $query->getBindings()];
} elseif (is_string($query)) {
return [$query, []];
Expand Down
15 changes: 15 additions & 0 deletions tests/Database/DatabaseEloquentBuilderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -637,6 +637,21 @@ public function testWithCountAndMergedWheres()
$this->assertEquals(['qux', true], $builder->getBindings());
}

public function testWithCountAndGlobalScope()
{
$model = new EloquentBuilderTestModelParentStub;
EloquentBuilderTestModelCloseRelatedStub::addGlobalScope('withCount', function ($query) {
return $query->addSelect('id');
});

$builder = $model->select('id')->withCount(['foo']);

// Remove the global scope so it doesn't interfere with any other tests
EloquentBuilderTestModelCloseRelatedStub::addGlobalScope('withCount', function ($query) {});

$this->assertEquals('select "id", (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 testWithCountAndContraintsAndHaving()
{
$model = new EloquentBuilderTestModelParentStub;
Expand Down

0 comments on commit 432816b

Please sign in to comment.