简体   繁体   中英

Laravel polymorphic relation with custom key

In my project I'm working on multiple databases and one central one. I'm using spatie's activity log package to log actions done form control panel to all of that databases.

I have table Items in each of the databases (except for the central) with auto incremented primary key, and another index called hash, which is kind of uuid. Hash is always unique.

Now, when I want to log actions, I can encounter problem as it will save ID of Item, so... in my activity tables I will get two records for subject_id = 1, while one activity happend to Item on one db and another on another, and so on.

How can I change set morphing to use my uuid column instead of id without changing $primaryKey on related model?

Item model relation:

public function activities(): MorphMany
{
    $this->morphMany(Activity::class, 'subject', 'subject_id', 'hash');
}

Activity model relation:

public function subject(): MorphTo
{
    if (config('activitylog.subject_returns_soft_deleted_models')) {
        return $this->morphTo()->withTrashed();
    }
    return $this->morphTo('activity_log', 'subject_type', 'subject_id', 'hash');
}

Also, I found in ActivityLogger:

public function performedOn(Model $model)
{
    $this->getActivity()->subject()->associate($model);

    return $this;
}

I ended up with temporary hack.

First of all, I've added a public method to my model:

public function setPrimaryKey(string $columnName)
{
    $this->primaryKey = $columnName;
    $this->keyType = 'string';
}

Later on I extended ActivityLogger class and implemented my own perfomedOn() method.

public function performedOn(Model $model)
{
    if($model instanceof Item::class) {
        $model->setPrimaryKey('hash');
    }

    return parent::performedOn($model);
}

I am aware it is not the best solution but kind of works for now.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM