Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cannot work with multiple model key types. #3653

Open
irealworlds opened this issue Jun 23, 2024 · 2 comments
Open

Cannot work with multiple model key types. #3653

irealworlds opened this issue Jun 23, 2024 · 2 comments

Comments

@irealworlds
Copy link

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.

@chrispage1
Copy link
Contributor

I think this is a problem you'd get regardless. Generally, I'd say its always best practice to have an ID for a record, and then if you want to use UUID's have a secondary column that stores the UUID.

@ElonSmithee
Copy link

Лучший вариант, в данном случае, это использование разных моделей/таблиц, что я пытаюсь сейчас сделать, но по какой-то причине, пакет не особо волнует, что я тут добавил.

use Spatie\MediaLibrary\MediaCollections\Models\Media;

class OtherMedia extends Media
{
    protected $table = 'other_media';
}
public function media(): MorphMany
{
    return $this->morphMany(OtherMedia::class, 'model');
}
Data truncated for column 'model_id' at row 1 (Connection: mysql, SQL: insert into `media`...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants