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

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 MAC安装佳能LBP2900驱动的网盘提取码
  • ¥400 微信停车小程序谁懂的来
  • ¥15 ATAC测序到底用什么peak文件做Diffbind差异分析
  • ¥15 安装ubantu过程中第一个vfat 文件挂载失败
  • ¥20 GZ::CTF如何兼容一些靶机?
  • ¥15 etcd集群部署问题
  • ¥20 谁可以帮我一下问一下各位
  • ¥15 为何重叠加权后love图的SMD与svyCreateTableOne函数绘制基线表的不一致
  • ¥150 求 《小魔指》街机游戏机整合模拟软件
  • ¥20 你好,我想问下easyExcel下拉多选,或者复选框可以实现吗