我正在尝试在 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');
}
}
但没有成功。
另外,我想问你是否可以告诉我如何编写“关注”和“显示关注者/关注”功能。我已经阅读了我能找到的所有教程,但没有用。我似乎无法理解。
你需要意识到“追随者”也是一个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');
}
User $a
想要关注用户$b
:
$a->following()->attach($b);
User $a
想要停止关注用户$b
:
$a->following()->detach($b);
获取用户的所有关注者$a
:
$a_followers = $a->followers()->get();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)