Skip to content

Commit 0ef45af

Browse files
committed
Aggregation shouldn't mutate querybuilder
Aggregations (like $query->count() ) modifies the internal state of the queryBuilder object, therefore the $query looses eg. the projection. Eloquent solves this in the following way: https://github.com/laravel/framework/blob/5.3/src/Illuminate/Database/Query/Builder.php#L2036
1 parent 8ab0293 commit 0ef45af

File tree

1 file changed

+15
-5
lines changed

1 file changed

+15
-5
lines changed

src/Jenssegers/Mongodb/Query/Builder.php

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -422,18 +422,28 @@ public function generateCacheKey()
422422
public function aggregate($function, $columns = [])
423423
{
424424
$this->aggregate = compact('function', 'columns');
425-
425+
426+
$previousColumns = $this->columns;
427+
428+
// We will also back up the select bindings since the select clause will be
429+
// removed when performing the aggregate function. Once the query is run
430+
// we will add the bindings back onto this query so they can get used.
431+
$previousSelectBindings = $this->bindings['select'];
432+
433+
$this->bindings['select'] = [];
434+
426435
$results = $this->get($columns);
427-
436+
428437
// Once we have executed the query, we will reset the aggregate property so
429438
// that more select queries can be executed against the database without
430439
// the aggregate value getting in the way when the grammar builds it.
431-
$this->columns = null;
432440
$this->aggregate = null;
433-
441+
$this->columns = $previousColumns;
442+
$this->bindings['select'] = $previousSelectBindings;
443+
434444
if (isset($results[0])) {
435445
$result = (array) $results[0];
436-
446+
437447
return $result['aggregate'];
438448
}
439449
}

0 commit comments

Comments
 (0)