Laravel的关注者/被关注者关系

8
我正在尝试在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();
    });

-粉丝迁移:

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个回答

18

你需要意识到“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();

哦,我的天啊!非常感谢! - MDeian
如果你想显示关注者的数量,你可以使用 $a->followers()->get()->count() 吗?还是应该将查询包装到 count 方法中? - DavidG
@Martin Heralecký 你是冠军! - Umer Fayyaz

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接