-
-
Notifications
You must be signed in to change notification settings - Fork 469
Expand file tree
/
Copy pathNestedOneToMany.php
More file actions
82 lines (69 loc) · 2.66 KB
/
Copy pathNestedOneToMany.php
File metadata and controls
82 lines (69 loc) · 2.66 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
<?php declare(strict_types=1);
namespace Nuwave\Lighthouse\Execution\Arguments;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\MorphMany;
use Nuwave\Lighthouse\Support\Contracts\ArgResolver;
class NestedOneToMany implements ArgResolver
{
public function __construct(
protected string $relationName,
) {}
/**
* @param \Illuminate\Database\Eloquent\Model $model
* @param ArgumentSet $args
*/
public function __invoke($model, $args): void
{
$relation = $model->{$this->relationName}();
assert($relation instanceof HasMany || $relation instanceof MorphMany);
if ($args->has('create')) {
$saveModel = new ResolveNested(new SaveModel($relation));
foreach ($args->arguments['create']->value as $childArgs) {
// @phpstan-ignore-next-line Relation&Builder mixin not recognized
$saveModel($relation->make(), $childArgs);
}
}
if ($args->has('update')) {
$updateModel = new ResolveNested(new UpdateModel(new SaveModel($relation)));
foreach ($args->arguments['update']->value as $childArgs) {
// @phpstan-ignore-next-line Relation&Builder mixin not recognized
$updateModel($relation->make(), $childArgs);
}
}
if ($args->has('upsert')) {
$upsertModel = new ResolveNested(new UpsertModel(new SaveModel($relation), $relation));
foreach ($args->arguments['upsert']->value as $childArgs) {
// @phpstan-ignore-next-line Relation&Builder mixin not recognized
$upsertModel($relation->make(), $childArgs);
}
}
if ($args->has('connect')) {
$children = $relation
->make()
->whereIn(
$relation->make()->getKeyName(),
$args->arguments['connect']->value,
)
->get();
$relation->saveMany($children);
}
if ($args->has('disconnect')) {
$children = $relation
->make()
->whereIn(
$relation->make()->getKeyName(),
$args->arguments['disconnect']->value,
)
->get();
foreach ($children as $child) {
$child->setAttribute($relation->getForeignKeyName(), null);
$child->save();
}
}
if ($args->has('delete')) {
$relation->getRelated()::destroy(
$args->arguments['delete']->toPlain(),
);
}
}
}