php - 如何制作链接两个用户 ID 的数据透视表?

标签 php mysql database laravel eloquent

比如说,我有这个 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 之间建立关系,或者将用户与配置文件或其他内容链接起来(但他们已经链接到他们自己的配置文件?),但我不知道如何。我有点迷路了。也许我看错了。

提前致谢。

最佳答案

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

编号 |用户 ID | follows_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

关于php - 如何制作链接两个用户 ID 的数据透视表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39604079/

相关文章:

php - 我是新手,需要 php 数组调用的帮助。我确实使用 var_dump 并显示了这个

php - 为什么我的 PHP 查询在页面加载时执行两次?

c# - 我的 sql 数据库备份在客户端的 .SQL 文件中?

database - 何时创建新的 RDS 实例与新数据库?

iOS - 对何时在我的应用程序中使用核心数据感到困惑

php - 没有根据where条件从数据库中获取正确的值

php - 在 php 中只运行一次更新查询

php - 在 WordPress 中获取随机帖子(带缩略图)

php - 离线更新数据库

php - 阿拉伯字符插入 php mysql XML 解析错误 : not well-formed