Skip to content

Commit

Permalink
Improve related save
Browse files Browse the repository at this point in the history
  • Loading branch information
Tofandel committed Jun 5, 2024
1 parent c217950 commit 432ad29
Showing 1 changed file with 13 additions and 8 deletions.
21 changes: 13 additions & 8 deletions src/Models/Behaviors/HasRelated.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -63,18 +62,24 @@ public function loadRelated(string $browserName): Collection
/**
* Attach items to the model for a browser field.
*
* @param array<int, TwillModelContract> $items
* @param array<int, Model|array> $items
*/
public function saveRelated(array|Collection $items, string $browserName): void
{
/** @var Collection<int, RelatedItem> $itemsToProcess */
$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();
Expand All @@ -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,
]);
Expand Down

0 comments on commit 432ad29

Please sign in to comment.