Skip to content

Commit 0556a4a

Browse files
ChrisAtUdemytaylorotwell
authored andcommitted
#23327 Moving code from the query builder to the eloquent builder (#23357)
A previous pull request #19013, which aimed to solve the issue of multiple select statements causing an SQL error within a withCount function, assumed a sub query would only need one select statement. This is not the case, so the code that removes excess filters is moved to the withCount method where the sub query does only need one select.
1 parent 075ba07 commit 0556a4a

File tree

3 files changed

+8
-5
lines changed

3 files changed

+8
-5
lines changed

src/Illuminate/Database/Eloquent/Concerns/QueriesRelationships.php

+6-2
Original file line numberDiff line numberDiff line change
@@ -210,14 +210,18 @@ public function withCount($relations)
210210

211211
$query->callScope($constraints);
212212

213-
$query->mergeConstraintsFrom($relation->getQuery());
213+
$query = $query->mergeConstraintsFrom($relation->getQuery())->toBase();
214+
215+
if (count($query->columns) > 1) {
216+
$query->columns = [$query->columns[0]];
217+
}
214218

215219
// Finally we will add the proper result column alias to the query and run the subselect
216220
// statement against the query builder. Then we will return the builder instance back
217221
// to the developer for further constraint chaining that needs to take place on it.
218222
$column = $alias ?? Str::snake($name.'_count');
219223

220-
$this->selectSub($query->toBase(), $column);
224+
$this->selectSub($query, $column);
221225
}
222226

223227
return $this;

src/Illuminate/Database/Query/Builder.php

-2
Original file line numberDiff line numberDiff line change
@@ -279,8 +279,6 @@ public function selectSub($query, $as)
279279
protected function parseSubSelect($query)
280280
{
281281
if ($query instanceof self) {
282-
$query->columns = [$query->columns[0]];
283-
284282
return [$query->toSql(), $query->getBindings()];
285283
} elseif (is_string($query)) {
286284
return [$query, []];

tests/Database/DatabaseQueryBuilderTest.php

+2-1
Original file line numberDiff line numberDiff line change
@@ -1449,10 +1449,11 @@ public function testAggregateWithSubSelect()
14491449
return $results;
14501450
});
14511451
$builder->from('users')->selectSub(function ($query) {
1452-
$query->from('posts')->select('foo')->where('title', 'foo');
1452+
$query->from('posts')->select('foo', 'bar')->where('title', 'foo');
14531453
}, 'post');
14541454
$count = $builder->count();
14551455
$this->assertEquals(1, $count);
1456+
$this->assertEquals('(select "foo", "bar" from "posts" where "title" = ?) as "post"', $builder->columns[0]->getValue());
14561457
$this->assertEquals(['foo'], $builder->getBindings());
14571458
}
14581459

0 commit comments

Comments
 (0)