首页 > 解决方案 > Laravel 将任何模型变形为用户模型

问题描述

我的任务是向用户添加加星标的项目。项目可以是(Sample、Publication、Message、atc..)。所有项目都是具有自己的表的 Eloquent 模型,如samples, publications,messages和主键id

我想通过一张表(user_starrable)将这些模型作为加星标的项目与用户相关联。该表的结构可以类似于

id - integer
user_id - integer

model_id - integer (value like 1)
model_type - string (value like \App\Models\Sample)

我试图通过变形关系来做这几天,但没有成功。我无法在模型上编写正确的方法来完成这项工作。最后,我需要通过代码查询一个集合中的所有模型,$user->starrables()->get()并且我希望将所有模型放在一起(样本、出版物和消息,如果存在关系)。谢谢!

楷模:

用户.php

class User
{
    protected $table = 'users';

    protected $hidden = [
        'password', 'remember_token',
    ];


    public function starred() { // that i cant write
        return $this->morphTo();
    }
}

示例.php

class Sample
{
    protected $table = 'samples';

    public function starrable() {
        return $this->morphOne(User::class, 'starred');
    }
}

发布.php

class Publication
{
    protected $table = 'publications';

    public function starrable() {
        return $this->morphOne(User::class, 'starred');
    }
}

消息.php

class Message
{
    protected $table = 'messages';

    public function starrable() {
        return $this->morphOne(User::class, 'starred');
    }
}

标签: databaselaraveleloquentpolymorphismrelation

解决方案


推荐阅读