设置关系以便用户可以通过相同的 table 关注多个模型类型

Setting up relationship so users can follow multiple model types through same table

我已经用我的头敲打我的键盘大约 2 个小时了,现在我试图解决这个问题,我终于到了我需要帮助的地步。

我希望 Users 能够通过 Follows table.

跟随 AlphaBeta 模型

理想情况下,代码可能如下所示:

$user = User::find(1);
$alpha = Alpha::find(1);
$beta = Beta::find(1);
$user->following()->save($alpha);
$user->following()->save($beta);

我已经尝试过使用常规多态关系和多对多多态关系,并取得了不同程度的成功。无论我尝试过什么,我都无法完全意识到这一点,我认为这只是精神上的疲惫让我在这一点上退缩了。

在我看来,这像是 UsersFollows 之间的一对多关系,然后是 FollowsAlphas/[=17 之间的传统多态关系=].

Table结构

alphas
    id - integer
    name - string

betas
    id - integer
    name - string

follows
    id - integer
    user_id - integer
    followable_id - integer
    followable_type - string

users
    id - integer

型号

class Follow extends Model
{
    public function followable()
    {
        return $this->morphTo();
    }

    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

class Alpha extends Model
{
    public function follows()
    {
        return $this->morphMany(Follow::class, 'followable');
    }
}

class Beta extends Model
{
    public function follows()
    {
        return $this->morphMany(Follow::class, 'followable');
    }
}

class User extends Model
{
    public function follows()
    {
        return $this->hasMany(Follow::class);
    }

    public function alphas()
    {
        return $this->follows()->where('followable_type', Alpha::class);
    }

    public function betas()
    {
        return $this->follows()->where('followable_type', Beta::class);
    }
}

保存关系

$user = User::find($uid);

$follow = new Follow([
    'user_id' => $user->id
]);

$alpha = Alpha::find($aid);

$alpha->follows()->save($follow);