Laravel Eloquent用户与朋友之间的关系

时间:2017-08-02 01:30:48

标签: php mysql laravel-5.4 laravel-eloquent

我对雄辩的关系感到困惑。我有两张桌子:

USERS:
id, name, pwd, etc...

FRIENDS:
id, user_id, friend_id

对于FRIENDS表,我有两个外键:

$t->foreign('user_id')
  ->references('id')
  ->on('users');

$t->foreign('friend_id')
  ->references('id')
  ->on('users');

在每节课中我都有以下关系:

USER类:

/**
 * A user can have many friends
 */
public function friends()
{
    return $this->hasMany(User::class, 'friend_id', 'id');
}

FRIEND课程:

/**
 * A friend can belong to a user
 */
public function friend()
{
    return $this->belongsTo(User::class, 'id', 'user_id');
}

/**
 * A user friends are connected to
 */
public function user()
{
    return $this->belongsTo(User::class, 'id', 'friend_id');
}

我想以

结束
Auth::user()->friends()->get();

这段关系应该是hasManyThrough()吗?当通过FRIENDS表自引用USERS表时,如何实现这一点?

2 个答案:

答案 0 :(得分:1)

迁移:

public function friends()
{
    return $this->belongsToMany(User::class, 'friend_user', 'user_id', 'friend_id');
}

用户模型:

Auth::user()->friends (or Auth::user()->friends()->get())

更新

结交所有朋友:

Auth::user()->friends()->attach([2,3,4]); // Add user_id 2, 3 and 4

添加好友:

Auth::user()->friends()->detach([2]); // Remove user_id = 2

删除朋友:

Auth::user()->friends()->sync([7]); // Remove old and add user_id = 7

同步朋友:

{{1}}

答案 1 :(得分:0)

没有friends表,因为有虚构的两个表users,又有users表,所以您不需要friends