laravel-medialibrary icon indicating copy to clipboard operation
laravel-medialibrary copied to clipboard

Cannot work with multiple model key types.

Open irealworlds opened this issue 8 months ago • 2 comments

As it currently stands, it is not possible to use this library (out of the box) when working with models with multiple key types (i.e. numeric ids on some models, but uuids on others).

I am using UUIDs for most of my models, so I modified the Media table migration to use uuids for model_id, but some use integers.

I could not find any way to achieve this other than a hacky solution like this, which is not DB agnostic and involves creating a custom trait

trait InteractsWithMediaUsingNumericKey
{
    public function media(): MorphMany
    {
        return $this->morphMany(
            $this->getMediaModel(),
            'model',
            localKey: DB::raw('CAST(id AS VARCHAR)')->getValue(
                DB::getQueryGrammar(),
            ),
        );
    }
}

The best solution I could think of is changing model_id to a json column and using a json representation of the actual model id for all models, but this requires a change in the HasMedia contract as well as the InteractsWithMedia trait, because then the relation returned by media() is no longer MorphMany, but a HasMany.

irealworlds avatar Jun 23 '24 19:06 irealworlds