diff --git a/src/Models/Behaviors/HasRelated.php b/src/Models/Behaviors/HasRelated.php index 29e6c1f7d..6580bfa51 100644 --- a/src/Models/Behaviors/HasRelated.php +++ b/src/Models/Behaviors/HasRelated.php @@ -2,10 +2,9 @@ namespace A17\Twill\Models\Behaviors; -use A17\Twill\Models\Contracts\TwillModelContract; use A17\Twill\Models\RelatedItem; +use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\MorphMany; -use Illuminate\Support\Arr; use Illuminate\Support\Collection; trait HasRelated @@ -63,7 +62,7 @@ public function loadRelated(string $browserName): Collection /** * Attach items to the model for a browser field. * - * @param array $items + * @param array $items */ public function saveRelated(array|Collection $items, string $browserName): void { @@ -71,10 +70,16 @@ public function saveRelated(array|Collection $items, string $browserName): void $itemsToProcess = $this->relatedItems()->where('browser_name', $browserName)->get(); foreach ($items as $position => $item) { + if ($item instanceof Model) { + $id = $item->getKey(); + $type = $item->getMorphClass(); + } else { + $id = $item['id']; + $type = $item['endpointType']; + } + $firstMatchKey = $itemsToProcess - ->where('related_id', $item['id']) - ->where('related_type', $item['endpointType']) - ->where('browser_name', $browserName) + ->where(fn ($item) => $item->related_id === $id && $item->related_type === $type) // We should only have one item always as you cannot select the same items twice. ->keys() ->first(); @@ -90,8 +95,8 @@ public function saveRelated(array|Collection $items, string $browserName): void RelatedItem::create([ 'subject_id' => $this->getKey(), 'subject_type' => $this->getMorphClass(), - 'related_id' => $item['id'], - 'related_type' => $item['endpointType'], + 'related_id' => $id, + 'related_type' => $type, 'browser_name' => $browserName, 'position' => $position + 1, ]);