-
Notifications
You must be signed in to change notification settings - Fork 11.2k
/
Copy pathCanBeOneOfMany.php
310 lines (265 loc) · 8.93 KB
/
CanBeOneOfMany.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
<?php
namespace Illuminate\Database\Eloquent\Relations\Concerns;
use Closure;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Query\JoinClause;
use Illuminate\Support\Arr;
use InvalidArgumentException;
trait CanBeOneOfMany
{
/**
* Determines whether the relationship is one-of-many.
*
* @var bool
*/
protected $isOneOfMany = false;
/**
* The name of the relationship.
*
* @var string
*/
protected $relationName;
/**
* The one of many inner join subselect query builder instance.
*
* @var \Illuminate\Database\Eloquent\Builder|null
*/
protected $oneOfManySubQuery;
/**
* Add constraints for inner join subselect for one of many relationships.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param string|null $column
* @param string|null $aggregate
* @return void
*/
abstract public function addOneOfManySubQueryConstraints(Builder $query, $column = null, $aggregate = null);
/**
* Get the columns the determine the relationship groups.
*
* @return array|string
*/
abstract public function getOneOfManySubQuerySelectColumns();
/**
* Add join query constraints for one of many relationships.
*
* @param \Illuminate\Database\Query\JoinClause $join
* @return void
*/
abstract public function addOneOfManyJoinSubQueryConstraints(JoinClause $join);
/**
* Indicate that the relation is a single result of a larger one-to-many relationship.
*
* @param string|array|null $column
* @param string|\Closure|null $aggregate
* @param string|null $relation
* @return $this
*
* @throws \InvalidArgumentException
*/
public function ofMany($column = 'id', $aggregate = 'MAX', $relation = null)
{
$this->isOneOfMany = true;
$this->relationName = $relation ?: $this->getDefaultOneOfManyJoinAlias(
$this->guessRelationship()
);
$keyName = $this->query->getModel()->getKeyName();
$columns = is_string($columns = $column) ? [
$column => $aggregate,
$keyName => $aggregate,
] : $column;
if (! array_key_exists($keyName, $columns)) {
$columns[$keyName] = 'MAX';
}
if ($aggregate instanceof Closure) {
$closure = $aggregate;
}
foreach ($columns as $column => $aggregate) {
if (! in_array(strtolower($aggregate), ['min', 'max'])) {
throw new InvalidArgumentException("Invalid aggregate [{$aggregate}] used within ofMany relation. Available aggregates: MIN, MAX");
}
$subQuery = $this->newOneOfManySubQuery(
$this->getOneOfManySubQuerySelectColumns(),
$column, $aggregate
);
if (isset($previous)) {
$this->addOneOfManyJoinSubQuery($subQuery, $previous['subQuery'], $previous['column']);
}
if (isset($closure)) {
$closure($subQuery);
}
if (! isset($previous)) {
$this->oneOfManySubQuery = $subQuery;
}
if (array_key_last($columns) == $column) {
$this->addOneOfManyJoinSubQuery($this->query, $subQuery, $column);
}
$previous = [
'subQuery' => $subQuery,
'column' => $column,
];
}
$this->addConstraints();
$columns = $this->query->getQuery()->columns;
if (is_null($columns) || $columns === ['*']) {
$this->select([$this->qualifyColumn('*')]);
}
return $this;
}
/**
* Indicate that the relation is the latest single result of a larger one-to-many relationship.
*
* @param string|array|null $column
* @param string|null $relation
* @return $this
*/
public function latestOfMany($column = 'id', $relation = null)
{
return $this->ofMany(collect(Arr::wrap($column))->mapWithKeys(function ($column) {
return [$column => 'MAX'];
})->all(), 'MAX', $relation);
}
/**
* Indicate that the relation is the oldest single result of a larger one-to-many relationship.
*
* @param string|array|null $column
* @param string|null $relation
* @return $this
*/
public function oldestOfMany($column = 'id', $relation = null)
{
return $this->ofMany(collect(Arr::wrap($column))->mapWithKeys(function ($column) {
return [$column => 'MIN'];
})->all(), 'MIN', $relation);
}
/**
* Get the default alias for the one of many inner join clause.
*
* @param string $relation
* @return string
*/
protected function getDefaultOneOfManyJoinAlias($relation)
{
return $relation == $this->query->getModel()->getTable()
? $relation.'_of_many'
: $relation;
}
/**
* Get a new query for the related model, grouping the query by the given column, often the foreign key of the relationship.
*
* @param string|array $groupBy
* @param string|null $column
* @param string|null $aggregate
* @return \Illuminate\Database\Eloquent\Builder
*/
protected function newOneOfManySubQuery($groupBy, $column = null, $aggregate = null)
{
$subQuery = $this->query->getModel()
->newQuery()
->withoutGlobalScopes($this->removedScopes());
foreach (Arr::wrap($groupBy) as $group) {
$subQuery->groupBy($this->qualifyRelatedColumn($group));
}
if (! is_null($column)) {
$subQuery->selectRaw($aggregate.'('.$subQuery->getQuery()->grammar->wrap($subQuery->qualifyColumn($column)).') as '.$subQuery->getQuery()->grammar->wrap($column.'_aggregate'));
}
$this->addOneOfManySubQueryConstraints($subQuery, $groupBy, $column, $aggregate);
return $subQuery;
}
/**
* Add the join subquery to the given query on the given column and the relationship's foreign key.
*
* @param \Illuminate\Database\Eloquent\Builder $parent
* @param \Illuminate\Database\Eloquent\Builder $subQuery
* @param string $on
* @return void
*/
protected function addOneOfManyJoinSubQuery(Builder $parent, Builder $subQuery, $on)
{
$parent->beforeQuery(function ($parent) use ($subQuery, $on) {
$subQuery->applyBeforeQueryCallbacks();
$parent->joinSub($subQuery, $this->relationName, function ($join) use ($on) {
$join->on($this->qualifySubSelectColumn($on.'_aggregate'), '=', $this->qualifyRelatedColumn($on));
$this->addOneOfManyJoinSubQueryConstraints($join, $on);
});
});
}
/**
* Merge the relationship query joins to the given query builder.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @return void
*/
protected function mergeOneOfManyJoinsTo(Builder $query)
{
$query->getQuery()->beforeQueryCallbacks = $this->query->getQuery()->beforeQueryCallbacks;
$query->applyBeforeQueryCallbacks();
}
/**
* Get the query builder that will contain the relationship constraints.
*
* @return \Illuminate\Database\Eloquent\Builder
*/
protected function getRelationQuery()
{
return $this->isOneOfMany()
? $this->oneOfManySubQuery
: $this->query;
}
/**
* Get the one of many inner join subselect builder instance.
*
* @return \Illuminate\Database\Eloquent\Builder|void
*/
public function getOneOfManySubQuery()
{
return $this->oneOfManySubQuery;
}
/**
* Get the qualified column name for the one-of-many relationship using the subselect join query's alias.
*
* @param string $column
* @return string
*/
public function qualifySubSelectColumn($column)
{
return $this->getRelationName().'.'.last(explode('.', $column));
}
/**
* Qualify related column using the related table name if it is not already qualified.
*
* @param string $column
* @return string
*/
protected function qualifyRelatedColumn($column)
{
return str_contains($column, '.') ? $column : $this->query->getModel()->getTable().'.'.$column;
}
/**
* Guess the "hasOne" relationship's name via backtrace.
*
* @return string
*/
protected function guessRelationship()
{
return debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 3)[2]['function'];
}
/**
* Determine whether the relationship is a one-of-many relationship.
*
* @return bool
*/
public function isOneOfMany()
{
return $this->isOneOfMany;
}
/**
* Get the name of the relationship.
*
* @return string
*/
public function getRelationName()
{
return $this->relationName;
}
}