I used the one-to-many polymorphic relationship like described in the laravel documentation, to be able to relate different parent models to one child model. i have assumed, that i would be able to assign different parent models to the same child model. but this does not work. as soon as i create a new relation with another parent model to the same child, the old relation is replaced.
Example:
A
, B
and C
are parent models, each with one data-record (id=1
).
X
is the child model with one data-record (id=1
)
I can't do something like that with the common methods:
A
(id=1
) <-> X
(id=1
)
B
(id=1
) <-> X
(id=1
)
C
(id=1
) <-> X
(id=1
)
Since the last creation of a relation always overwrites the previous one. In this example one relation would remain (C
(id=1
) <-> X
(id=1
))
I am able to do that with a many-to-many polymorphic implementation - but this is actually not what i want, since i do not want the parent models to be able to have more than one relation to the child model. (altough i could rule that out by creating a composite key within the *able
table on the corresponding fields)
This is the actual code, that should assign one image to multiple parent models (but only the last save inside the loop remains - if i add a break at the end of the loop, the first one is saved):
public function store(StoreImageRequest $request)
{
$validated = $request->validated();
$image = $validated['image'];
$name = isset($validated['clientName']) ? $image->getClientOriginalName() : $validated['name'];
$fileFormat = FileFormat::where('mimetype','=',$image->getClientMimeType())->first();
$path = $image->store('images');
$imageModel = Image::make(['name' => $name, 'path' => $path])->fileFormat()->associate($fileFormat);
$imageModel->save();
$relatedModels = Image::getRelatedModels();
foreach($relatedModels as $fqcn => $cn) {
if(isset($validated['model'.$cn])) {
$id = $validated['model'.$cn];
$models[$fqcn] = call_user_func([$fqcn, 'find'], [$id])->first();
$models[$fqcn]->images()->save($imageModel);
}
}
}