Skip to content

Commit 2608b18

Browse files
authored
Merge pull request #83 from phpsa/feature/pivot-values
Update Relationships.php
2 parents 1f7f3cf + 8dc41f3 commit 2608b18

File tree

1 file changed

+22
-6
lines changed

1 file changed

+22
-6
lines changed

src/Contracts/Relationships.php

Lines changed: 22 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,7 @@ protected function storeRelated($item, array $includes, array $data): void
112112
throw new ApiException("$type mapping not implemented yet");
113113
break;
114114
}
115+
$item->load($with);
115116
}
116117
}
117118

@@ -184,23 +185,38 @@ protected function processBelongsToManyRelation($relation, array $relatedRecords
184185
$model = $relation->getRelated();
185186
$sync = collect();
186187

188+
$pivots = $relation->getPivotColumns();
189+
$detach = filter_var(request()->get('sync')[$with] ?? false, FILTER_VALIDATE_BOOLEAN);
190+
187191
foreach ($relatedRecords as $relatedRecord) {
192+
188193
if (! isset($relatedRecord[$parentKey])) {
189194
$relatedRecord[$parentKey] = $item->getAttribute($relatedKey);
190195
}
191196
if ($relatedRecord[$parentKey]) {
192197
$existanceCheck = [$parentKey => $relatedRecord[$parentKey]];
193-
$sync->push($model->updateOrCreate($existanceCheck, $relatedRecord));
198+
$record = $model->updateOrCreate($existanceCheck, $relatedRecord);
194199
} elseif (isset($data[$relatedKey])) {
195200
$existanceCheck = [$parentKey => $data[$relatedKey]];
196-
$sync->push($model->updateOrCreate($existanceCheck, $relatedRecord));
201+
$record = $model->updateOrCreate($existanceCheck, $relatedRecord);
197202
} else {
198-
$sync->push($model->create($relatedRecord));
203+
$record = $model->create($relatedRecord);
199204
}
200-
}
201205

202-
$detach = filter_var(request()->get('sync')[$with] ?? false, FILTER_VALIDATE_BOOLEAN);
206+
$pvals = [];
207+
if($pivots){
208+
209+
foreach($pivots as $pivot)
210+
{
211+
if(isset($relatedRecord[$pivot])){
212+
$pvals[$pivot] = $relatedRecord[$pivot];
213+
}
214+
}
215+
}
216+
$sync->put($record->getKey(), $pvals);
217+
218+
}
203219

204-
$relation->sync($sync->pluck('id'), $detach);
220+
$relation->sync($sync->toArray(), $detach);
205221
}
206222
}

0 commit comments

Comments
 (0)