gpt4 book ai didi

php - Laravel 追随者/跟随关系

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:04:39 26 4
gpt4 key购买 nike

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

但是没用。

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

最佳答案

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

关于php - Laravel 追随者/跟随关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44913409/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com