Laravel追随者/以下关系

时间:2017-07-04 20:08:56

标签: php laravel relationships

我想在laravel中创建一个简单的关注者/关注系统,没什么特别的,只需点击一个按钮即可关注或取消关注,并显示关注者或跟随你的人。

我的麻烦是我无法弄清楚如何建立模型之间的关系。

这些是迁移:

- 用户迁移:

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();
    });

-Followers migration:

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');
    }

}

- 追随者模型基本上是空的,这就是我被卡住的地方

我试过这样的事情:

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

但它不起作用。

另外,我想问你是否可以告诉我如何编写“跟随”和“显示关注者/关注”功能。我已经阅读了我能找到的每个教程,但没有用。我似乎无法理解。

1 个答案:

答案 0 :(得分:7)

你需要意识到"追随者"也是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();