Skip to content

Commit 924735e

Browse files
author
Marcel Gwerder
committed
Fixed issue where global scopes were not applied for counts
1 parent 1743354 commit 924735e

File tree

2 files changed

+20
-4
lines changed

2 files changed

+20
-4
lines changed

src/CountMetaProvider.php

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,8 @@
1-
<?php namespace Marcelgwerder\ApiHandler;
1+
<?php
2+
3+
namespace Marcelgwerder\ApiHandler;
4+
5+
use \Illuminate\Database\Query\Builder as QueryBuilder;
26

37
class CountMetaProvider extends MetaProvider
48
{
@@ -11,7 +15,18 @@ class CountMetaProvider extends MetaProvider
1115

1216
public function __construct($title, $builder)
1317
{
14-
$this->builder = clone $builder;
18+
$builder = clone $builder;
19+
20+
if($builder instanceof QueryBuilder) {
21+
$this->builder = $builder;
22+
} else if(method_exists($builder, 'toBase')) {
23+
// Laravel > 5.2 as global scopes, toBase makes sure they are included.
24+
$this->builder = $builder->toBase();
25+
} else {
26+
// Laravel < 5.2 did not have global scopes and thus the query builder is enough.
27+
$this->builder = $builder->getQuery();
28+
}
29+
1530
$this->title = $title;
1631

1732
//Remove offset from builder because a count doesn't work in combination with an offset
@@ -36,6 +51,7 @@ public function get()
3651

3752
//Use the original builder as a subquery and count over it because counts over groups return the number of rows for each group, not for the total results
3853
$query = $this->builder->newQuery()->selectRaw('count(*) as aggregate from (' . $this->builder->toSql() . ') as count_table', $this->builder->getBindings());
54+
3955
return intval($query->first()->aggregate);
4056
}
4157

src/Parser.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -649,9 +649,9 @@ protected function parseConfig($configParam)
649649
}
650650
} else if ($cat == 'meta') {
651651
if ($option == 'total-count') {
652-
$this->meta[] = new CountMetaProvider('Meta-Total-Count', $this->originalQuery);
652+
$this->meta[] = new CountMetaProvider('Meta-Total-Count', $this->originalBuilder);
653653
} else if ($option == 'filter-count') {
654-
$this->meta[] = new CountMetaProvider('Meta-Filter-Count', $this->query);
654+
$this->meta[] = new CountMetaProvider('Meta-Filter-Count', $this->builder);
655655
}
656656
} else if ($cat == 'response') {
657657
if ($option == 'envelope') {

0 commit comments

Comments
 (0)