Skip to content

Commit

Permalink
[5.1] Fixed aggregate queries (#14793)
Browse files Browse the repository at this point in the history
* Fixed aggregate queries

* Tweaks
  • Loading branch information
GrahamCampbell authored and taylorotwell committed Aug 12, 2016
1 parent 092bea0 commit 73ee91b
Showing 1 changed file with 15 additions and 14 deletions.
29 changes: 15 additions & 14 deletions src/Illuminate/Database/Query/Builder.php
Original file line number Diff line number Diff line change
Expand Up @@ -1668,7 +1668,7 @@ public function count($columns = '*')
*/
public function min($column)
{
return $this->aggregate(__FUNCTION__, [$column]);
return $this->numericAggregate(__FUNCTION__, [$column]);
}

/**
Expand All @@ -1679,7 +1679,7 @@ public function min($column)
*/
public function max($column)
{
return $this->aggregate(__FUNCTION__, [$column]);
return $this->numericAggregate(__FUNCTION__, [$column]);
}

/**
Expand All @@ -1690,9 +1690,7 @@ public function max($column)
*/
public function sum($column)
{
$result = $this->aggregate(__FUNCTION__, [$column]);

return $result ?: 0;
return $this->numericAggregate(__FUNCTION__, [$column]);
}

/**
Expand All @@ -1703,7 +1701,7 @@ public function sum($column)
*/
public function avg($column)
{
return $this->aggregate(__FUNCTION__, [$column]);
return $this->numericAggregate(__FUNCTION__, [$column]);
}

/**
Expand All @@ -1722,7 +1720,7 @@ public function average($column)
*
* @param string $function
* @param array $columns
* @return float|int
* @return mixed
*/
public function aggregate($function, $columns = ['*'])
{
Expand All @@ -1749,21 +1747,24 @@ public function aggregate($function, $columns = ['*'])
$this->bindings['select'] = $previousSelectBindings;

if (isset($results[0])) {
return $this->formatAggregate($results);
return array_change_key_case((array) $results[0])['aggregate'];
}

return 0;
}

/**
* Format the return value of an aggregate function.
* Execute a numeric aggregate function on the database.
*
* @param array $results
* @param string $function
* @param array $columns
* @return float|int
*/
protected function formatAggregate($results)
public function numericAggregate($function, $columns = ['*'])
{
$result = array_change_key_case((array) $results[0])['aggregate'];
$result = $this->aggregate($function, $columns);

if (! $result) {
return 0;
}

if (is_int($result) || is_float($result)) {
return $result;
Expand Down

0 comments on commit 73ee91b

Please sign in to comment.