Skip to content

Bug: Avg method with columns (like avg('something')) for union query fails with exception #56314

@vismutx

Description

@vismutx

Laravel Version

12.20.0

PHP Version

8.3

Database Driver & Version

No response

Description

For union queries Avg method fails with exception

The used SELECT statements have a different number of columns

problem is here. ->get($columns) change select for first union subquery with that columns

    public function aggregate($function, $columns = ['*'])
    {
        $results = $this->cloneWithout($this->unions || $this->havings ? [] : ['columns'])
            ->cloneWithoutBindings($this->unions || $this->havings ? [] : ['select'])
            ->setAggregate($function, $columns)
            ->get($columns);

        if (! $results->isEmpty()) {
            return array_change_key_case((array) $results[0])['aggregate'];
        }
    }

Steps To Reproduce

  1. Any union query
  2. ->avg('column')
  3. as result
select avg(column) as aggregate from ((select column from table where id = 1) union (select * from table where id = 2))

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions