1 | <?php |
||
2 | |||
3 | namespace Bakery\Mutations; |
||
4 | |||
5 | use Bakery\Fields\Field; |
||
6 | use Illuminate\Support\Str; |
||
7 | use Bakery\Support\Arguments; |
||
8 | use Illuminate\Support\Facades\DB; |
||
9 | use Illuminate\Database\Eloquent\Model; |
||
10 | use Bakery\Types\Concerns\InteractsWithPivot; |
||
11 | use Illuminate\Database\Eloquent\Relations\BelongsToMany; |
||
12 | |||
13 | class AttachPivotMutation extends EloquentMutation |
||
14 | { |
||
15 | use InteractsWithPivot; |
||
16 | |||
17 | /** |
||
18 | * Get the name of the mutation. |
||
19 | * |
||
20 | * @return string |
||
21 | */ |
||
22 | public function name(): string |
||
23 | { |
||
24 | if (isset($this->name)) { |
||
25 | return $this->name; |
||
26 | } |
||
27 | |||
28 | $relation = Str::studly($this->pivotRelationName); |
||
29 | |||
30 | return 'attach'.$relation.'On'.$this->modelSchema->getTypename(); |
||
31 | } |
||
32 | |||
33 | /** |
||
34 | * Get the arguments of the mutation. |
||
35 | * |
||
36 | * @return array |
||
37 | */ |
||
38 | public function args(): array |
||
39 | { |
||
40 | $relation = $this->relation->getRelationName(); |
||
41 | |||
42 | if ($this->getPivotModelSchema()) { |
||
43 | $typename = Str::studly($relation).'PivotInput'; |
||
44 | $type = $this->registry->type($typename)->list(); |
||
45 | } else { |
||
46 | $type = $this->registry->ID()->list(); |
||
47 | } |
||
48 | |||
49 | return $this->modelSchema->getLookupFields() |
||
50 | ->map(function (Field $field) { |
||
51 | return $field->getType(); |
||
52 | }) |
||
53 | ->merge(['input' => $type]) |
||
54 | ->toArray(); |
||
55 | } |
||
56 | |||
57 | /** |
||
58 | * Get the pivot relation. |
||
59 | * |
||
60 | * @param \Illuminate\Database\Eloquent\Model $model |
||
61 | * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany |
||
62 | */ |
||
63 | protected function getRelation(Model $model): BelongsToMany |
||
64 | { |
||
65 | return $model->{$this->pivotRelationName}(); |
||
66 | } |
||
67 | |||
68 | /** |
||
69 | * Resolve the mutation. |
||
70 | * |
||
71 | * @param Arguments $args |
||
72 | * @return Model |
||
73 | */ |
||
74 | public function resolve(Arguments $args): Model |
||
75 | { |
||
76 | $input = $args->input->toArray(); |
||
0 ignored issues
–
show
Bug
introduced
by
![]() |
|||
77 | $model = $this->findOrFail($args); |
||
78 | |||
79 | return DB::transaction(function () use ($input, $model) { |
||
80 | $modelSchema = $this->registry->getSchemaForModel($model); |
||
81 | |||
82 | $relation = $this->getRelation($model); |
||
83 | |||
84 | $modelSchema->connectBelongsToManyRelation($relation, $input, false); |
||
85 | $modelSchema->save(); |
||
86 | |||
87 | // Refresh the model to accommodate for any side effects |
||
88 | // that the pivot relation may have caused. |
||
89 | return $modelSchema->getInstance()->refresh(); |
||
90 | }); |
||
91 | } |
||
92 | } |
||
93 |