Laravel follower/following 关系

Laravel follower/following relationships

我正在尝试在laravel中做一个简单的follower/following系统,没什么特别的,只需单击一个按钮即可关注或取消关注,并显示关注者或关注您的人。

我的问题是我不知道如何建立模型之间的关系。

这些是迁移:

-用户迁移:

Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->timestamps();
        $table->string('email');
        $table->string('first_name');
        $table->string('last_name');
        $table->string('password');
        $table->string('gender');
        $table->date('dob');
        $table->rememberToken();
    });

-关注者迁移:

Schema::create('followers', function (Blueprint $table) {

        $table->increments('id');
        $table->integer('follower_id')->unsigned();
        $table->integer('following_id')->unsigned();
        $table->timestamps();        
    });
}

以下是模型:

-用户模型:

   class User extends Model implements Authenticatable
{
    use \Illuminate\Auth\Authenticatable;
    public function posts()
    {
        return $this->hasMany('App\Post');
    }

    public function followers()
    {
        return $this->hasMany('App\Followers');
    }

}

-而followers模型基本上是空的,这就是我卡住的地方

我试过这样的事情:

class Followers extends Model
{
    public function user()
    {
        return $this->belongsTo('App\User');
    }
}

但是没用。

另外,请教一下"follow"和"display followers/following"函数的写法。我已经阅读了我能找到的所有教程,但没有用。看不懂。

你需要意识到 "follower" 也是一个 App\User。所以你只需要一个模型 App\User 和这两种方法:

// users that are followed by this user
public function following() {
    return $this->belongsToMany(User::class, 'followers', 'follower_id', 'following_id');
}

// users that follow this user
public function followers() {
    return $this->belongsToMany(User::class, 'followers', 'following_id', 'follower_id');
}

用户 $a 想要关注用户 $b:

$a->following()->attach($b);

用户 $a 想停止关注用户 $b:

$a->following()->detach($b);

获取用户$a的所有关注者:

$a_followers = $a->followers()->get();