【问题标题】:How to make a pivot table linking two user ID's?如何制作链接两个用户 ID 的数据透视表?
【发布时间】:2016-09-20 21:32:50
【问题描述】:

说,我有这个 Laravel 5.3 设置

用户表

id | name | password

用户模型

class User extends Authenticatable
{
    public function profile()
    {
        return $this->hasOne('App\Profile');
    }
}

个人资料表

id | user_id

个人资料模型

class Profile extends Model
{

    public function user()
    {
        $this->belongsTo('App\User');
    }
}

现在我希望人们能够关注彼此的个人资料。我需要制作一个在两个user_id 之间建立关系的数据透视表,或者将用户与个人资料或其他东西联系起来(但他们已经链接到自己的个人资料?),但我不知道如何。我有点迷路了。也许我看错了。

提前致谢。

【问题讨论】:

    标签: php mysql database laravel eloquent


    【解决方案1】:

    为什么不使用具有以下结构的user_follows 表:

    标识 |用户 ID | follow_id

    那么你可以分别获取用户关注的用户和关注用户的用户:

    public function follows()
    {
        return $this->belongsToMany('App\User', 'user_follows', 'user_id', 'follows_id');
    }
    
    
    public function followers()
    {
        return $this->belongsToMany('App\User', 'user_follows', 'follows_id', 'user_id');
    }
    

    在此处查看有多少多对多关系有效: https://laravel.com/docs/5.3/eloquent-relationships#many-to-many

    【讨论】:

      猜你喜欢
      • 2020-06-20
      • 2021-10-20
      • 1970-01-01
      • 1970-01-01
      • 2016-11-26
      • 2021-02-06
      • 1970-01-01
      • 2016-10-02
      • 1970-01-01
      相关资源
      最近更新 更多