比如说,我有这个 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/