1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Staudenmeir\EloquentEagerLimit\Grammars\Traits; |
4
|
|
|
|
5
|
|
|
use Illuminate\Database\Query\Builder; |
6
|
|
|
|
7
|
|
|
trait CompilesGroupLimit |
8
|
|
|
{ |
9
|
|
|
/** |
10
|
|
|
* Compile a select query into SQL. |
11
|
|
|
* |
12
|
|
|
* @param \Illuminate\Database\Query\Builder $query |
13
|
|
|
* @return string |
14
|
|
|
*/ |
15
|
148 |
|
public function compileSelect(Builder $query) |
16
|
|
|
{ |
17
|
148 |
|
if (isset($query->groupLimit)) { |
18
|
116 |
|
if (is_null($query->columns)) { |
|
|
|
|
19
|
20 |
|
$query->columns = ['*']; |
20
|
|
|
} |
21
|
|
|
|
22
|
116 |
|
return $this->compileGroupLimit($query); |
23
|
|
|
} |
24
|
|
|
|
25
|
132 |
|
return parent::compileSelect($query); |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* Compile a group limit clause. |
30
|
|
|
* |
31
|
|
|
* @param \Illuminate\Database\Query\Builder $query |
32
|
|
|
* @return string |
33
|
|
|
*/ |
34
|
92 |
|
protected function compileGroupLimit(Builder $query) |
35
|
|
|
{ |
36
|
92 |
|
$selectBindings = array_merge($query->getRawBindings()['select'], $query->getRawBindings()['order']); |
37
|
|
|
|
38
|
92 |
|
$query->setBindings($selectBindings, 'select'); |
39
|
92 |
|
$query->setBindings([], 'order'); |
40
|
|
|
|
41
|
92 |
|
$limit = (int) $query->groupLimit['value']; |
|
|
|
|
42
|
|
|
|
43
|
92 |
|
$offset = $query->offset; |
44
|
|
|
|
45
|
92 |
|
if (isset($offset)) { |
46
|
44 |
|
$limit += (int) $offset; |
47
|
|
|
|
48
|
44 |
|
$query->offset = null; |
49
|
|
|
} |
50
|
|
|
|
51
|
92 |
|
$components = $this->compileComponents($query); |
|
|
|
|
52
|
|
|
|
53
|
92 |
|
$components['columns'] .= $this->compileRowNumber($query->groupLimit['column'], $components['orders'] ?? ''); |
54
|
|
|
|
55
|
92 |
|
unset($components['orders']); |
56
|
|
|
|
57
|
92 |
|
$sql = $this->concatenate($components); |
|
|
|
|
58
|
|
|
|
59
|
92 |
|
$sql = 'select * from ('.$sql.') as laravel_table where laravel_row <= '.$limit; |
60
|
|
|
|
61
|
92 |
|
if (isset($offset)) { |
62
|
44 |
|
$sql .= ' and laravel_row > '.(int) $offset; |
63
|
|
|
} |
64
|
|
|
|
65
|
92 |
|
return $sql.' order by laravel_row'; |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
/** |
69
|
|
|
* Compile a row number clause. |
70
|
|
|
* |
71
|
|
|
* @param string $partition |
72
|
|
|
* @param string $orders |
73
|
|
|
* @return string |
74
|
|
|
*/ |
75
|
92 |
|
protected function compileRowNumber($partition, $orders) |
76
|
|
|
{ |
77
|
92 |
|
$partition = 'partition by '.$this->wrap($partition); |
|
|
|
|
78
|
|
|
|
79
|
92 |
|
$over = trim($partition.' '.$orders); |
80
|
|
|
|
81
|
92 |
|
return ', row_number() over ('.$over.') as laravel_row'; |
82
|
|
|
} |
83
|
|
|
} |
84
|
|
|
|