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.

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

报告相同问题?

悬赏问题

  • ¥30 vmware exsi重置后的密码
  • ¥15 易盾点选的cb参数怎么解啊
  • ¥15 MATLAB运行显示错误,如何解决?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?
  • ¥15 电磁场的matlab仿真
  • ¥15 mars2d在vue3中的引入问题
  • ¥50 h5唤醒支付宝并跳转至向小荷包转账界面