Skip to content

Instantly share code, notes, and snippets.

@mcordingley
Created June 21, 2017 18:14
Show Gist options
  • Select an option

  • Save mcordingley/27ccca6b4b111cd46fdf4bd14f005c7f to your computer and use it in GitHub Desktop.

Select an option

Save mcordingley/27ccca6b4b111cd46fdf4bd14f005c7f to your computer and use it in GitHub Desktop.

Revisions

  1. mcordingley created this gist Jun 21, 2017.
    34 changes: 34 additions & 0 deletions fetchSynced.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,34 @@
    <?php

    /**
    * Takes the results of a relation sync and replaces the ids with model instances.
    *
    * @param array $synced The results of a call to `sync()` on a `BelongsToMany` relation.
    * @param string $foreign Namespaced model name. e.g. from Foo::class
    * @return array $sync, but with ids replaced with model instances
    */
    function fetchSynced(array $synced, string $foreign): array
    {
    /** @var Model $instance */
    $instance = new $foreign;

    $changes = [];
    $keyToType = [];

    foreach ($synced as $type => $keys) {
    $changes[$type] = [];

    foreach ($keys as $key) {
    $keyToType[$key] = $type;
    }
    }

    $fetched = $keyToType ? $foreign::whereIn($instance->getKeyName(), array_keys($keyToType))->get() : new Collection;

    /** @var Model $model */
    foreach ($fetched as $model) {
    $changes[$keyToType[$model->getKey()]][] = $model;
    }

    return $changes;
    }