Laravel Eloquent 用户与朋友的关系

Laravel Eloquent relationship for user to friends

我对 eloquent 关系感到困惑。我有两个 tables:

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

FRIENDS:
id, user_id, friend_id

对于朋友table,我有两个外键:

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

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

在每个 class 中,我有以下关系:

用户class:

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

朋友class:

/**
 * 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()吗?当 USERS table 通过 FRIENDS table?

自引用时,我该如何实现这一点

迁移:

public function up()
{
    Schema::create('friend_user', function(Blueprint $table) {
        $table->increments('id');
        $table->integer('friend_id')->unsigned()->index();
        $table->integer('user_id')->unsigned()->index();
        $table->foreign('friend_id')->references('id')->on('users')->onDelete('cascade');
        $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
    });
}

用户模型:

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

不需要friendstable,因为有虚数2tableusersuserstable,也就是为什么你不需要 friends table