-
Notifications
You must be signed in to change notification settings - Fork 88
/
Copy pathEloquentJoinBuilder.php
378 lines (306 loc) · 13 KB
/
EloquentJoinBuilder.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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
<?php
namespace Fico7489\Laravel\EloquentJoin;
use Fico7489\Laravel\EloquentJoin\Exceptions\InvalidAggregateMethod;
use Fico7489\Laravel\EloquentJoin\Exceptions\InvalidDirection;
use Fico7489\Laravel\EloquentJoin\Exceptions\InvalidRelation;
use Fico7489\Laravel\EloquentJoin\Exceptions\InvalidRelationClause;
use Fico7489\Laravel\EloquentJoin\Exceptions\InvalidRelationGlobalScope;
use Fico7489\Laravel\EloquentJoin\Exceptions\InvalidRelationWhere;
use Fico7489\Laravel\EloquentJoin\Relations\BelongsToJoin;
use Fico7489\Laravel\EloquentJoin\Relations\HasManyJoin;
use Fico7489\Laravel\EloquentJoin\Relations\HasOneJoin;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Database\Eloquent\SoftDeletingScope;
use Illuminate\Database\Query\JoinClause;
class EloquentJoinBuilder extends Builder
{
//constants
const AGGREGATE_SUM = 'SUM';
const AGGREGATE_AVG = 'AVG';
const AGGREGATE_MAX = 'MAX';
const AGGREGATE_MIN = 'MIN';
const AGGREGATE_COUNT = 'COUNT';
//use table alias for join (real table name or random sha1)
protected $useTableAlias = false;
//appendRelationsCount
protected $appendRelationsCount = false;
//leftJoin
protected $leftJoin = true;
//aggregate method
protected $aggregateMethod = self::AGGREGATE_MAX;
//base builder
protected $baseBuilder;
//store if ->select(...) is already called on builder (we want only one groupBy())
protected $selected = false;
//store joined tables, we want join table only once (e.g. when you call orderByJoin more time)
protected $joinedTables = [];
//store clauses on relation for join
public $relationClauses = [];
//query methods
public function where($column, $operator = null, $value = null, $boolean = 'and')
{
if ($column instanceof \Closure) {
$query = $this->model->newModelQuery();
$baseBuilderCurrent = $this->baseBuilder ? $this->baseBuilder : $this;
$query->baseBuilder = $baseBuilderCurrent;
$column($query);
$this->query->addNestedWhereQuery($query->getQuery(), $boolean);
} else {
$this->query->where(...func_get_args());
}
return $this;
}
public function whereJoin($column, $operator, $value, $boolean = 'and')
{
$query = $this->baseBuilder ? $this->baseBuilder : $this;
$column = $query->performJoin($column);
return $this->where($column, $operator, $value, $boolean);
}
public function orWhereJoin($column, $operator, $value)
{
$query = $this->baseBuilder ? $this->baseBuilder : $this;
$column = $query->performJoin($column);
return $this->orWhere($column, $operator, $value);
}
public function whereInJoin($column, $values, $boolean = 'and', $not = false)
{
$query = $this->baseBuilder ? $this->baseBuilder : $this;
$column = $query->performJoin($column);
return $this->whereIn($column, $values, $boolean, $not);
}
public function whereNotInJoin($column, $values, $boolean = 'and')
{
$query = $this->baseBuilder ? $this->baseBuilder : $this;
$column = $query->performJoin($column);
return $this->whereNotIn($column, $values, $boolean);
}
public function orWhereInJoin($column, $values)
{
$query = $this->baseBuilder ? $this->baseBuilder : $this;
$column = $query->performJoin($column);
return $this->orWhereIn($column, $values);
}
public function orWhereNotInJoin($column, $values)
{
$query = $this->baseBuilder ? $this->baseBuilder : $this;
$column = $query->performJoin($column);
return $this->orWhereNotIn($column, $values);
}
public function orderByJoin($column, $direction = 'asc', $aggregateMethod = null)
{
$direction = strtolower($direction);
$this->checkDirection($direction);
$dotPos = strrpos($column, '.');
$query = $this->baseBuilder ? $this->baseBuilder : $this;
$column = $query->performJoin($column);
if (false !== $dotPos) {
//order by related table field
$aggregateMethod = $aggregateMethod ? $aggregateMethod : $this->aggregateMethod;
$this->checkAggregateMethod($aggregateMethod);
$sortsCount = count($this->query->orders ?? []);
$sortAlias = 'sort'.(0 == $sortsCount ? '' : ($sortsCount + 1));
$grammar = \DB::query()->getGrammar();
$query->selectRaw($aggregateMethod.'('.$grammar->wrap($column).') as '.$sortAlias);
return $this->orderByRaw($sortAlias.' '.$direction);
}
//order by base table field
return $this->orderBy($column, $direction);
}
/**
* Joining relations.
*
* @param string|array $relations
* @param bool|null $leftJoin
*
* @return $this
*
* @throws InvalidRelation
*/
public function joinRelations($relations, $leftJoin = null)
{
$leftJoin = null !== $leftJoin ? $leftJoin : $this->leftJoin;
$query = $this->baseBuilder ? $this->baseBuilder : $this;
if (is_array($relations)) {
foreach ($relations as $relation) {
$query->joinRelations($relation, $leftJoin);
}
} else {
$query->performJoin($relations.'.FAKE_FIELD', $leftJoin);
}
return $this;
}
//helpers methods
protected function performJoin($relations, $leftJoin = null)
{
//detect join method
$leftJoin = null !== $leftJoin ? $leftJoin : $this->leftJoin;
$joinMethod = $leftJoin ? 'leftJoin' : 'join';
//detect current model data
$relations = explode('.', $relations);
$column = end($relations);
$baseModel = $this->getModel();
$baseTable = $baseModel->getTable();
$basePrimaryKey = $baseModel->getKeyName();
$currentModel = $baseModel;
$currentTableAlias = $baseTable;
$relationsAccumulated = [];
foreach ($relations as $relation) {
if ($relation == $column) {
//last item in $relations argument is sort|where column
break;
}
/** @var Relation $relatedRelation */
$relatedRelation = $currentModel->$relation();
$relatedModel = $relatedRelation->getRelated();
$relatedPrimaryKey = $relatedModel->getKeyName();
$relatedTable = $relatedModel->getTable();
$relatedTableAlias = $this->useTableAlias ? sha1($relatedTable.rand()) : $relatedTable;
$relationsAccumulated[] = $relatedTableAlias;
$relationAccumulatedString = implode('_', $relationsAccumulated);
//relations count
if ($this->appendRelationsCount) {
$this->selectRaw('COUNT('.$relatedTableAlias.'.'.$relatedPrimaryKey.') as '.$relationAccumulatedString.'_count');
}
if (!in_array($relationAccumulatedString, $this->joinedTables)) {
$joinQuery = $relatedTable.($this->useTableAlias ? ' as '.$relatedTableAlias : '');
if ($relatedRelation instanceof BelongsToJoin) {
$relatedKey = is_callable([$relatedRelation, 'getQualifiedForeignKeyName']) ? $relatedRelation->getQualifiedForeignKeyName() : $relatedRelation->getQualifiedForeignKey();
$relatedKey = last(explode('.', $relatedKey));
$ownerKey = is_callable([$relatedRelation, 'getOwnerKeyName']) ? $relatedRelation->getOwnerKeyName() : $relatedRelation->getOwnerKey();
$this->$joinMethod($joinQuery, function ($join) use ($relatedRelation, $relatedTableAlias, $relatedKey, $currentTableAlias, $ownerKey) {
$join->on($relatedTableAlias.'.'.$ownerKey, '=', $currentTableAlias.'.'.$relatedKey);
$this->joinQuery($join, $relatedRelation, $relatedTableAlias);
});
} elseif ($relatedRelation instanceof HasOneJoin || $relatedRelation instanceof HasManyJoin) {
$relatedKey = $relatedRelation->getQualifiedForeignKeyName();
$relatedKey = last(explode('.', $relatedKey));
$localKey = $relatedRelation->getQualifiedParentKeyName();
$localKey = last(explode('.', $localKey));
$this->$joinMethod($joinQuery, function ($join) use ($relatedRelation, $relatedTableAlias, $relatedKey, $currentTableAlias, $localKey) {
$join->on($relatedTableAlias.'.'.$relatedKey, '=', $currentTableAlias.'.'.$localKey);
$this->joinQuery($join, $relatedRelation, $relatedTableAlias);
});
} else {
throw new InvalidRelation();
}
}
$currentModel = $relatedModel;
$currentTableAlias = $relatedTableAlias;
$this->joinedTables[] = implode('_', $relationsAccumulated);
}
if (!$this->selected && count($relations) > 1) {
$this->selected = true;
$this->selectRaw($baseTable.'.*');
$this->groupBy($baseTable.'.'.$basePrimaryKey);
}
return $currentTableAlias.'.'.$column;
}
protected function joinQuery($join, $relation, $relatedTableAlias)
{
/** @var Builder $relationQuery */
$relationBuilder = $relation->getQuery();
//apply clauses on relation
if (isset($relationBuilder->relationClauses)) {
foreach ($relationBuilder->relationClauses as $clause) {
foreach ($clause as $method => $params) {
$this->applyClauseOnRelation($join, $method, $params, $relatedTableAlias);
}
}
}
//apply global SoftDeletingScope
foreach ($relationBuilder->scopes as $scope) {
if ($scope instanceof SoftDeletingScope) {
$this->applyClauseOnRelation($join, 'withoutTrashed', [], $relatedTableAlias);
} else {
throw new InvalidRelationGlobalScope();
}
}
}
private function applyClauseOnRelation(JoinClause $join, string $method, array $params, string $relatedTableAlias)
{
if (in_array($method, ['where', 'orWhere'])) {
try {
if (is_array($params[0])) {
foreach ($params[0] as $k => $param) {
$params[0][$relatedTableAlias.'.'.$k] = $param;
unset($params[0][$k]);
}
} elseif (is_callable($params[0])) {
throw new InvalidRelationWhere();
} else {
$params[0] = $relatedTableAlias.'.'.$params[0];
}
call_user_func_array([$join, $method], $params);
} catch (\Exception $e) {
throw new InvalidRelationWhere();
}
} elseif (in_array($method, ['withoutTrashed', 'onlyTrashed', 'withTrashed'])) {
if ('withTrashed' == $method) {
//do nothing
} elseif ('withoutTrashed' == $method) {
call_user_func_array([$join, 'where'], [$relatedTableAlias.'.deleted_at', '=', null]);
} elseif ('onlyTrashed' == $method) {
call_user_func_array([$join, 'where'], [$relatedTableAlias.'.deleted_at', '<>', null]);
}
} else {
throw new InvalidRelationClause();
}
}
private function checkAggregateMethod($aggregateMethod)
{
if (!in_array($aggregateMethod, [
self::AGGREGATE_SUM,
self::AGGREGATE_AVG,
self::AGGREGATE_MAX,
self::AGGREGATE_MIN,
self::AGGREGATE_COUNT,
])) {
throw new InvalidAggregateMethod();
}
}
private function checkDirection($direction)
{
if (!in_array($direction, ['asc', 'desc'], true)) {
throw new InvalidDirection();
}
}
//getters and setters
public function isUseTableAlias(): bool
{
return $this->useTableAlias;
}
public function setUseTableAlias(bool $useTableAlias)
{
$this->useTableAlias = $useTableAlias;
return $this;
}
public function isLeftJoin(): bool
{
return $this->leftJoin;
}
public function setLeftJoin(bool $leftJoin)
{
$this->leftJoin = $leftJoin;
return $this;
}
public function isAppendRelationsCount(): bool
{
return $this->appendRelationsCount;
}
public function setAppendRelationsCount(bool $appendRelationsCount)
{
$this->appendRelationsCount = $appendRelationsCount;
return $this;
}
public function getAggregateMethod(): string
{
return $this->aggregateMethod;
}
public function setAggregateMethod(string $aggregateMethod)
{
$this->checkAggregateMethod($aggregateMethod);
$this->aggregateMethod = $aggregateMethod;
return $this;
}
}