Skip to content

Instantly share code, notes, and snippets.

@mcordingley
Created June 21, 2017 18:14
Show Gist options
  • Save mcordingley/27ccca6b4b111cd46fdf4bd14f005c7f to your computer and use it in GitHub Desktop.
Save mcordingley/27ccca6b4b111cd46fdf4bd14f005c7f to your computer and use it in GitHub Desktop.
<?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