Created
June 21, 2017 18:14
-
-
Save mcordingley/27ccca6b4b111cd46fdf4bd14f005c7f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment