Skip to content

Commit 5a92f04

Browse files
authored
fix #37483 (aggregates with having) (#37487)
1 parent 3f39024 commit 5a92f04

File tree

3 files changed

+19
-3
lines changed

3 files changed

+19
-3
lines changed

src/Illuminate/Database/Query/Builder.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2826,8 +2826,8 @@ public function average($column)
28262826
*/
28272827
public function aggregate($function, $columns = ['*'])
28282828
{
2829-
$results = $this->cloneWithout($this->unions ? [] : ['columns'])
2830-
->cloneWithoutBindings($this->unions ? [] : ['select'])
2829+
$results = $this->cloneWithout($this->unions || $this->havings ? [] : ['columns'])
2830+
->cloneWithoutBindings($this->unions || $this->havings ? [] : ['select'])
28312831
->setAggregate($function, $columns)
28322832
->get($columns);
28332833

src/Illuminate/Database/Query/Grammars/Grammar.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ class Grammar extends BaseGrammar
4545
*/
4646
public function compileSelect(Builder $query)
4747
{
48-
if ($query->unions && $query->aggregate) {
48+
if (($query->unions || $query->havings) && $query->aggregate) {
4949
return $this->compileUnionAggregate($query);
5050
}
5151

tests/Database/DatabaseQueryBuilderTest.php

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1034,6 +1034,22 @@ public function testUnionAggregate()
10341034
$builder->from('posts')->union($this->getSqlServerBuilder()->from('videos'))->count();
10351035
}
10361036

1037+
public function testHavingAggregate()
1038+
{
1039+
$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`';
1040+
$builder = $this->getMySqlBuilder();
1041+
$builder->getConnection()->shouldReceive('getDatabaseName');
1042+
$builder->getConnection()->shouldReceive('select')->once()->with($expected, [0 => 1], true)->andReturn([['aggregate' => 1]]);
1043+
$builder->getProcessor()->shouldReceive('processSelect')->once()->andReturnUsing(function ($builder, $results) {
1044+
return $results;
1045+
});
1046+
1047+
$builder->from('posts')->selectSub(function ($query) {
1048+
$query->from('videos')->select('count(*)')->whereColumn('posts.id', '=', 'videos.post_id');
1049+
}, 'videos_count')->having('videos_count', '>', 1);
1050+
$builder->count();
1051+
}
1052+
10371053
public function testSubSelectWhereIns()
10381054
{
10391055
$builder = $this->getBuilder();

0 commit comments

Comments
 (0)