Repository navigation
Expand file tree
/
Copy pathHasOneOrMany.php
More file actions
executable file
·428 lines (370 loc) · 11 KB
/
Copy pathHasOneOrMany.php
File metadata and controls
executable file
·428 lines (370 loc) · 11 KB
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
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
<?php
declare(strict_types=1);
/**
* This file is part of Hyperf.
*
* @link https://www.hyperf.io
* @document https://hyperf.wiki
* @contact [email protected]
* @license https://github.com/hyperf/hyperf/blob/master/LICENSE
*/
namespace Hyperf\Database\Model\Relations;
use Hyperf\Database\Exception\UniqueConstraintViolationException;
use Hyperf\Database\Model\Builder;
use Hyperf\Database\Model\Collection;
use Hyperf\Database\Model\Model;
use Traversable;
use function Hyperf\Tappable\tap;
/**
* @template TRelatedModel of \Hyperf\Database\Model\Model
* @template TDeclaringModel of \Hyperf\Database\Model\Model
* @template TResult
*
* @extends Relation<TRelatedModel, TDeclaringModel, TResult>
*/
abstract class HasOneOrMany extends Relation
{
/**
* The foreign key of the parent model.
*
* @var string
*/
protected $foreignKey;
/**
* The local key of the parent model.
*
* @var string
*/
protected $localKey;
/**
* The count of self joins.
*
* @var int
*/
protected static $selfJoinCount = 0;
/**
* Create a new has one or many relationship instance.
*
* @param string $foreignKey
* @param string $localKey
*/
public function __construct(Builder $query, Model $parent, $foreignKey, $localKey)
{
$this->localKey = $localKey;
$this->foreignKey = $foreignKey;
parent::__construct($query, $parent);
}
/**
* Create and return an un-saved instance of the related model.
*
* @return TRelatedModel
*/
public function make(array $attributes = [])
{
return tap($this->related->newInstance($attributes), function ($instance) {
$this->setForeignAttributesForCreate($instance);
});
}
/**
* Set the base constraints on the relation query.
*/
public function addConstraints()
{
if (Constraint::isConstraint()) {
$this->query->where($this->foreignKey, '=', $this->getParentKey());
$this->query->whereNotNull($this->foreignKey);
}
}
/**
* Set the constraints for an eager load of the relation.
*/
public function addEagerConstraints(array $models)
{
$whereIn = $this->whereInMethod($this->parent, $this->localKey);
$this->query->{$whereIn}(
$this->foreignKey,
$this->getKeys($models, $this->localKey)
);
}
/**
* Match the eagerly loaded results to their single parents.
*
* @param string $relation
* @return array
*/
public function matchOne(array $models, Collection $results, $relation)
{
return $this->matchOneOrMany($models, $results, $relation, 'one');
}
/**
* Match the eagerly loaded results to their many parents.
*
* @param string $relation
* @return array
*/
public function matchMany(array $models, Collection $results, $relation)
{
return $this->matchOneOrMany($models, $results, $relation, 'many');
}
/**
* Find a model by its primary key or return new instance of the related model.
*
* @param mixed $id
* @param array $columns
* @return TRelatedModel
*/
public function findOrNew($id, $columns = ['*'])
{
if (is_null($instance = $this->find($id, $columns))) {
$instance = $this->related->newInstance();
$this->setForeignAttributesForCreate($instance);
}
return $instance;
}
/**
* Get the first related model record matching the attributes or instantiate it.
*
* @return TRelatedModel
*/
public function firstOrNew(array $attributes, array $values = [])
{
if (is_null($instance = $this->where($attributes)->first())) {
$instance = $this->related->newInstance($attributes + $values);
$this->setForeignAttributesForCreate($instance);
}
return $instance;
}
/**
* Get the first related record matching the attributes. If the record is not found, create it.
*
* @return TRelatedModel
*/
public function firstOrCreate(array $attributes, array $values = [])
{
if (is_null($instance = $this->where($attributes)->first())) {
$instance = $this->create($attributes + $values);
}
return $instance;
}
/**
* Attempt to create the record. If a unique constraint violation occurs, attempt to find the matching record.
*
* @return TRelatedModel
*/
public function createOrFirst(array $attributes = [], array $values = [])
{
try {
return $this->create(array_merge($attributes, $values));
} catch (UniqueConstraintViolationException $exception) {
return $this->where($attributes)->first();
}
}
/**
* Create or update a related record matching the attributes, and fill it with values.
*
* @return TRelatedModel
*/
public function updateOrCreate(array $attributes, array $values = [])
{
return tap($this->firstOrNew($attributes), function ($instance) use ($values) {
$instance->fill($values);
$instance->save();
});
}
/**
* Attach a model instance to the parent model.
*
* @param TRelatedModel $model
* @return false|TRelatedModel
*/
public function save(Model $model)
{
$this->setForeignAttributesForCreate($model);
return $model->save() ? $model : false;
}
/**
* Attach a collection of models to the parent instance.
*
* @param array|Traversable $models
* @return array|Traversable
*/
public function saveMany($models)
{
foreach ($models as $model) {
$this->save($model);
}
return $models;
}
/**
* Create a new instance of the related model.
*
* @return TRelatedModel
*/
public function create(array $attributes = [])
{
return tap($this->related->newInstance($attributes), function ($instance) {
$this->setForeignAttributesForCreate($instance);
$instance->save();
});
}
/**
* Create a Collection of new instances of the related model.
*
* @return Collection<int, TRelatedModel>
*/
public function createMany(array $records)
{
$instances = $this->related->newCollection();
foreach ($records as $record) {
$instances->push($this->create($record));
}
return $instances;
}
/**
* Perform an update on all the related models.
*
* @return int
*/
public function update(array $attributes)
{
if ($this->related->usesTimestamps() && ! is_null($this->relatedUpdatedAt())) {
$attributes[$this->relatedUpdatedAt()] = $this->related->freshTimestampString();
}
return $this->query->update($attributes);
}
/**
* Add the constraints for a relationship query.
*
* @param array|mixed $columns
* @return Builder
*/
public function getRelationExistenceQuery(Builder $query, Builder $parentQuery, $columns = ['*'])
{
if ($query->getQuery()->from == $parentQuery->getQuery()->from) {
return $this->getRelationExistenceQueryForSelfRelation($query, $parentQuery, $columns);
}
return parent::getRelationExistenceQuery($query, $parentQuery, $columns);
}
/**
* Add the constraints for a relationship query on the same table.
*
* @param array|mixed $columns
* @return Builder
*/
public function getRelationExistenceQueryForSelfRelation(Builder $query, Builder $parentQuery, $columns = ['*'])
{
$query->from($query->getModel()->getTable() . ' as ' . $hash = $this->getRelationCountHash());
$query->getModel()->setTable($hash);
return $query->select($columns)->whereColumn(
$this->getQualifiedParentKeyName(),
'=',
$hash . '.' . $this->getForeignKeyName()
);
}
/**
* Get the key for comparing against the parent key in "has" query.
*
* @return string
*/
public function getExistenceCompareKey()
{
return $this->getQualifiedForeignKeyName();
}
/**
* Get the key value of the parent's local key.
*/
public function getParentKey()
{
return $this->parent->getAttribute($this->localKey);
}
/**
* Get the fully qualified parent key name.
*
* @return string
*/
public function getQualifiedParentKeyName()
{
return $this->parent->qualifyColumn($this->localKey);
}
/**
* Get the plain foreign key.
*
* @return string
*/
public function getForeignKeyName()
{
$segments = explode('.', $this->getQualifiedForeignKeyName());
return end($segments);
}
/**
* Get the foreign key for the relationship.
*
* @return string
*/
public function getQualifiedForeignKeyName()
{
return $this->foreignKey;
}
/**
* Get the local key for the relationship.
*
* @return string
*/
public function getLocalKeyName()
{
return $this->localKey;
}
/**
* Match the eagerly loaded results to their many parents.
*
* @param string $relation
* @param string $type
* @return array
*/
protected function matchOneOrMany(array $models, Collection $results, $relation, $type)
{
$dictionary = $this->buildDictionary($results);
// Once we have the dictionary we can simply spin through the parent models to
// link them up with their children using the keyed dictionary to make the
// matching very convenient and easy work. Then we'll just return them.
foreach ($models as $model) {
if (isset($dictionary[$key = $model->getAttribute($this->localKey)])) {
$model->setRelation(
$relation,
$this->getRelationValue($dictionary, $key, $type)
);
}
}
return $models;
}
/**
* Get the value of a relationship by one or many type.
*
* @param string $key
* @param string $type
*/
protected function getRelationValue(array $dictionary, $key, $type)
{
$value = $dictionary[$key];
return $type === 'one' ? reset($value) : $this->related->newCollection($value);
}
/**
* Build model dictionary keyed by the relation's foreign key.
*
* @return array
*/
protected function buildDictionary(Collection $results)
{
$foreign = $this->getForeignKeyName();
return $results->mapToDictionary(function ($result) use ($foreign) {
return [$result->{$foreign} => $result];
})->all();
}
/**
* Set the foreign ID for creating a related model.
*/
protected function setForeignAttributesForCreate(Model $model)
{
$model->setAttribute($this->getForeignKeyName(), $this->getParentKey());
}
}