Skip to content

Commit

Permalink
Merge pull request #89 from uwpsych/options_from_models
Browse files Browse the repository at this point in the history
  • Loading branch information
kasparrosin committed Apr 27, 2021
2 parents f98db53 + 0934f12 commit aa4f0e4
Showing 1 changed file with 22 additions and 22 deletions.
44 changes: 22 additions & 22 deletions src/Multiselect.php
Original file line number Diff line number Diff line change
Expand Up @@ -72,13 +72,10 @@ public function api($path, $resourceClass)
}

try {
$options = [];
$modelObj = $this->resourceClass::newModel();
$models = $this->resourceClass::newModel()::whereIn($modelObj->getKeyName(), $value)->get();
$models->each(function ($model) use (&$options) {
$options[$model[$model->getKeyName()]] = (new $this->resourceClass($model))->title();
});
$this->options($options);
$models = $modelObj::whereIn($modelObj->getKeyName(), $value)->get();

$this->setOptionsFromModels($models);
} catch (Exception $e) {
}

Expand Down Expand Up @@ -260,11 +257,7 @@ public function belongsToMany($resourceClass, $async = true)

$models = $async ? $value : $resourceClass::newModel()::all();

$options = [];
$models->each(function ($model) use (&$options, $resourceClass) {
$options[$model[$model->getKeyName()]] = $model[$resourceClass::$title];
});
$this->options($options);
$this->setOptionsFromModels($models);

return $value->map(function ($model) {
return $model[$model->getKeyName()];
Expand Down Expand Up @@ -307,17 +300,10 @@ public function belongsTo($resourceClass, $async = true)
$value = $value->{$primaryKey} ?? null;
if ($async) $this->asyncResource($resourceClass);

$options = [];
if ($async && isset($value)) {
$model = $resourceClass::newModel()::find($value);
if (isset($model)) $options[$model[$primaryKey]] = $model[$resourceClass::$title];
} else {
$models = $resourceClass::newModel()::all();
$models->each(function ($model) use (&$options, $resourceClass) {
$options[$model[$model->getKeyName()]] = $model[$resourceClass::$title];
});
}
$this->options($options);
$model = $resourceClass::newModel();
$models = $async && isset($value) ? collect([$model::find($value)]) : $model::all();

$this->setOptionsFromModels($models);

return $value;
});
Expand Down Expand Up @@ -347,4 +333,18 @@ public function clearOnSelect($clearOnSelect = true)
{
return $this->withMeta(['clearOnSelect' => $clearOnSelect]);
}

/**
* Set the options from a collection of models.
*
* @param \Illuminate\Database\Eloquent\Collection $models
* @return void
*/
public function setOptionsFromModels(Collection $models)
{
$options = $models->mapInto($this->resourceClass)->mapWithKeys(function ($associatedResource) {
return [$associatedResource->getKey() => $associatedResource->title()];
});
$this->options($options);
}
}

0 comments on commit aa4f0e4

Please sign in to comment.