Skip to content

Commit

Permalink
Merge pull request #1018 from lee-to/json-related-keys-as-relation
Browse files Browse the repository at this point in the history
fix: Json asRelation
  • Loading branch information
lee-to authored Jun 3, 2024
2 parents 6cc3dfd + beb04c3 commit a1d0b3f
Showing 1 changed file with 13 additions and 8 deletions.
21 changes: 13 additions & 8 deletions src/Fields/Json.php
Original file line number Diff line number Diff line change
Expand Up @@ -549,28 +549,33 @@ private function saveRelation(array $items, mixed $model)
{
$items = collect($items);

$relationName = $this->column();

$related = $model->{$relationName}()->getRelated();

$relatedKeyName = $related->getKeyName();
$relatedQualifiedKeyName = $related->getQualifiedKeyName();

$ids = $items
->pluck($model->{$this->column()}()->getLocalKeyName())
->pluck($relatedKeyName)
->filter()
->toArray();

$localKeyName = $model->{$this->column()}()->getLocalKeyName();

$model->{$this->column()}()->when(
$model->{$relationName}()->when(
! empty($ids),
fn (Builder $q) => $q->whereNotIn(
$localKeyName,
$relatedQualifiedKeyName,
$ids
)->delete()
);

$model->{$this->column()}()->when(
$model->{$relationName}()->when(
empty($ids) && $this->asRelationDeleteWhenEmpty,
fn (Builder $q) => $q->delete()
);

$items->each(fn ($item) => $model->{$this->column()}()->updateOrCreate(
[$localKeyName => $item[$localKeyName] ?? null],
$items->each(fn ($item) => $model->{$relationName}()->updateOrCreate(
[$relatedQualifiedKeyName => $item[$relatedKeyName] ?? null],
$item
));

Expand Down

0 comments on commit a1d0b3f

Please sign in to comment.