Skip to content

Commit 432816b

Browse files
committed
Fix bug related to sub select queries and extra select statements.
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.
1 parent f7e9f74 commit 432816b

File tree

2 files changed

+16
-0
lines changed

2 files changed

+16
-0
lines changed

src/Illuminate/Database/Query/Builder.php

+1
Original file line numberDiff line numberDiff line change
@@ -279,6 +279,7 @@ public function selectSub($query, $as)
279279
protected function parseSubSelect($query)
280280
{
281281
if ($query instanceof self) {
282+
$query->columns = [$query->columns[0]];
282283
return [$query->toSql(), $query->getBindings()];
283284
} elseif (is_string($query)) {
284285
return [$query, []];

tests/Database/DatabaseEloquentBuilderTest.php

+15
Original file line numberDiff line numberDiff line change
@@ -637,6 +637,21 @@ public function testWithCountAndMergedWheres()
637637
$this->assertEquals(['qux', true], $builder->getBindings());
638638
}
639639

640+
public function testWithCountAndGlobalScope()
641+
{
642+
$model = new EloquentBuilderTestModelParentStub;
643+
EloquentBuilderTestModelCloseRelatedStub::addGlobalScope('withCount', function ($query) {
644+
return $query->addSelect('id');
645+
});
646+
647+
$builder = $model->select('id')->withCount(['foo']);
648+
649+
// Remove the global scope so it doesn't interfere with any other tests
650+
EloquentBuilderTestModelCloseRelatedStub::addGlobalScope('withCount', function ($query) {});
651+
652+
$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());
653+
}
654+
640655
public function testWithCountAndContraintsAndHaving()
641656
{
642657
$model = new EloquentBuilderTestModelParentStub;

0 commit comments

Comments
 (0)