Skip to content

Commit

Permalink
fix #37483 (aggregates with having) (#37487)
Browse files Browse the repository at this point in the history
  • Loading branch information
Tofandel authored May 26, 2021
1 parent 3f39024 commit 5a92f04
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 3 deletions.
4 changes: 2 additions & 2 deletions src/Illuminate/Database/Query/Builder.php
Original file line number Diff line number Diff line change
Expand Up @@ -2826,8 +2826,8 @@ public function average($column)
*/
public function aggregate($function, $columns = ['*'])
{
$results = $this->cloneWithout($this->unions ? [] : ['columns'])
->cloneWithoutBindings($this->unions ? [] : ['select'])
$results = $this->cloneWithout($this->unions || $this->havings ? [] : ['columns'])
->cloneWithoutBindings($this->unions || $this->havings ? [] : ['select'])
->setAggregate($function, $columns)
->get($columns);

Expand Down
2 changes: 1 addition & 1 deletion src/Illuminate/Database/Query/Grammars/Grammar.php
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ class Grammar extends BaseGrammar
*/
public function compileSelect(Builder $query)
{
if ($query->unions && $query->aggregate) {
if (($query->unions || $query->havings) && $query->aggregate) {
return $this->compileUnionAggregate($query);
}

Expand Down
16 changes: 16 additions & 0 deletions tests/Database/DatabaseQueryBuilderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1034,6 +1034,22 @@ public function testUnionAggregate()
$builder->from('posts')->union($this->getSqlServerBuilder()->from('videos'))->count();
}

public function testHavingAggregate()
{
$expected = 'select count(*) as aggregate from (select (select `count(*)` from `videos` where `posts`.`id` = `videos`.`post_id`) as `videos_count` from `posts` having `videos_count` > ?) as `temp_table`';
$builder = $this->getMySqlBuilder();
$builder->getConnection()->shouldReceive('getDatabaseName');
$builder->getConnection()->shouldReceive('select')->once()->with($expected, [0 => 1], true)->andReturn([['aggregate' => 1]]);
$builder->getProcessor()->shouldReceive('processSelect')->once()->andReturnUsing(function ($builder, $results) {
return $results;
});

$builder->from('posts')->selectSub(function ($query) {
$query->from('videos')->select('count(*)')->whereColumn('posts.id', '=', 'videos.post_id');
}, 'videos_count')->having('videos_count', '>', 1);
$builder->count();
}

public function testSubSelectWhereIns()
{
$builder = $this->getBuilder();
Expand Down

0 comments on commit 5a92f04

Please sign in to comment.