dqrzot2791 2019-05-20 08:05
浏览 290
已采纳

Laravel与自定义键的多态关系

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;
}
  • 写回答

1条回答 默认 最新

  • dongzhuo1930 2019-05-20 19:19
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器