Laravel follower/following relationships

一世执手 提交于 2020-01-22 15:34:27

问题


I am trying to make a simple follower/following system in laravel, nothing special, just click a button to follow or unfollow, and display the followers or the people following you.

My trouble is I can't figure out how to make the relationships between the models.

These are the migrations:

-User migration:

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

And here are the models:

-User model:

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

}

-And the followers model is basically empty, this is where I got stuck

I tried something like this:

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

but it didn't work.

Also, I'd like to ask if you could tell me how to write the "follow" and "display followers/following" functions. I've read every tutorial I could find but to no use. I can't seem to understand.


回答1:


You need to realize that the "follower" is also a App\User. So you only need one model App\User with these two methods:

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

User $a wants to follow user $b:

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

User $a wants to stop following user $b:

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

Get all followers of user $a:

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


来源:https://stackoverflow.com/questions/44913409/laravel-follower-following-relationships

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!