Skip to content

Commit d9a6143

Browse files
committed
Fix offset/limit in union query builder
1 parent 858cf46 commit d9a6143

File tree

1 file changed

+48
-9
lines changed

1 file changed

+48
-9
lines changed

src/Laravel/UnionBuilder.php

Lines changed: 48 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -8,11 +8,50 @@ class UnionBuilder implements Builder
88
{
99
private array $queryCalls = [];
1010
private array $outerQueryCalls = [];
11+
private ?int $limit = null;
12+
private int $offset = 0;
1113

1214
public function __construct(protected array $queries)
1315
{
1416
}
1517

18+
public function skip(int $value): static
19+
{
20+
return $this->offset($value);
21+
}
22+
23+
public function offset(int $value): static
24+
{
25+
$this->offset = max(0, $value);
26+
27+
return $this;
28+
}
29+
30+
public function take(?int $value): static
31+
{
32+
return $this->limit($value);
33+
}
34+
35+
public function limit(?int $value): static
36+
{
37+
if ($value >= 0) {
38+
$this->limit = $value;
39+
}
40+
41+
return $this;
42+
}
43+
44+
public function orderBy($column, $direction = 'asc'): static
45+
{
46+
$this->queryCalls[] = fn($query) => $query
47+
->addSelect($column)
48+
->orderBy($column, $direction);
49+
50+
$this->outerQueryCalls[] = fn($query) => $query->orderBy($column, $direction);
51+
52+
return $this;
53+
}
54+
1655
public function count($columns = '*'): int
1756
{
1857
return $this->buildQuery()->count($columns);
@@ -31,6 +70,10 @@ protected function buildQuery()
3170
foreach ($this->queryCalls as $call) {
3271
$call($query);
3372
}
73+
74+
if ($this->limit) {
75+
$query->take($this->offset + $this->limit);
76+
}
3477
}
3578

3679
$outerQuery = array_shift($queries);
@@ -43,20 +86,16 @@ protected function buildQuery()
4386
$call($outerQuery);
4487
}
4588

89+
if ($this->limit) {
90+
$outerQuery->skip($this->offset)->take($this->limit);
91+
}
92+
4693
return $outerQuery;
4794
}
4895

4996
public function __call($method, $parameters)
5097
{
51-
$call = $this->queryCalls[] = fn($query) => $query->$method(...$parameters);
52-
53-
if ($method === 'orderBy') {
54-
$this->queryCalls[] = fn($query) => $query->addSelect($parameters[0]);
55-
}
56-
57-
if (in_array($method, ['take', 'limit', 'skip', 'offset', 'orderBy'])) {
58-
$this->outerQueryCalls[] = $call;
59-
}
98+
$this->queryCalls[] = fn($query) => $query->$method(...$parameters);
6099

61100
return $this;
62101
}

0 commit comments

Comments
 (0)