Laravel追随者/以下关系 [英] Laravel follower/following relationships
问题描述
我试图在laravel中创建一个简单的关注者/关注者系统,没什么特别的,只需单击一个按钮即可关注或取消关注,并显示关注者或关注您的人.
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.
这些是迁移:
-用户迁移:
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');
}
}
-跟随者模型基本上是空的,这就是我被困住的地方
-And the followers model is basically empty, this is where I got stuck
我尝试过这样的事情:
class Followers extends Model
{
public function user()
{
return $this->belongsTo('App\User');
}
}
但是没有用.
此外,我想问一下您能否告诉我如何编写关注"和显示关注者/关注"功能.我已经阅读了所有可以找到但没有用的教程.我似乎听不懂.
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.
推荐答案
您需要意识到跟随者"也是App\User
.因此,您只需要使用以下两种方法的一个模型App\User
:
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');
}
用户$a
要关注用户$b
:
User $a
wants to follow user $b
:
$a->following()->attach($b);
用户$a
想要停止关注用户$b
:
User $a
wants to stop following user $b
:
$a->following()->detach($b);
获取用户$a
的所有关注者:
Get all followers of user $a
:
$a_followers = $a->followers()->get();
这篇关于Laravel追随者/以下关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!