Skip to content

Commit

Permalink
#23327 Moving code from the query builder to the eloquent builder (#2…
Browse files Browse the repository at this point in the history
…3357)

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.
  • Loading branch information
ChrisAtUdemy authored and taylorotwell committed Mar 1, 2018
1 parent 075ba07 commit 0556a4a
Show file tree
Hide file tree
Showing 3 changed files with 8 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -210,14 +210,18 @@ public function withCount($relations)

$query->callScope($constraints);

$query->mergeConstraintsFrom($relation->getQuery());
$query = $query->mergeConstraintsFrom($relation->getQuery())->toBase();

if (count($query->columns) > 1) {
$query->columns = [$query->columns[0]];
}

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

$this->selectSub($query->toBase(), $column);
$this->selectSub($query, $column);
}

return $this;
Expand Down
2 changes: 0 additions & 2 deletions src/Illuminate/Database/Query/Builder.php
Original file line number Diff line number Diff line change
Expand Up @@ -279,8 +279,6 @@ 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
3 changes: 2 additions & 1 deletion tests/Database/DatabaseQueryBuilderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1449,10 +1449,11 @@ public function testAggregateWithSubSelect()
return $results;
});
$builder->from('users')->selectSub(function ($query) {
$query->from('posts')->select('foo')->where('title', 'foo');
$query->from('posts')->select('foo', 'bar')->where('title', 'foo');
}, 'post');
$count = $builder->count();
$this->assertEquals(1, $count);
$this->assertEquals('(select "foo", "bar" from "posts" where "title" = ?) as "post"', $builder->columns[0]->getValue());
$this->assertEquals(['foo'], $builder->getBindings());
}

Expand Down

0 comments on commit 0556a4a

Please sign in to comment.