gpt4 book ai didi

mysql - 如何在关注或取消关注之前检查用户是否正在关注另一个用户(附件)

转载 作者:行者123 更新时间:2023-11-29 06:50:11 29 4
gpt4 key购买 nike

我在用户表中使用了多对多关系来使登录用户关注另一个用户,但我自己没有弄清楚,我检查了其他人做了什么,并尝试做类似的事情,并且它有效。在我的方法中,我有:

function follow(User $user) {
$this->followers()->attach($user->id);
}

function unfollow(User $user) {
$this->followers()->detach($user->id);
}

这让我可以跟随。

这些表与类似的函数相关:

return $this->belongsToMany('App\User', 'followers', 'user_id', 'follower_id');

现在我通过 Controller 传递 $user 值,并且 Controller 非常简单:

    $userId = User::find($user);
$willfollow = Auth::user();

$willfollow->unfollow($userId);

我知道可能不需要 Controller 信息,但如果很容易检查 Controller 内的关系,我更愿意这样做,因为我显然对方法使用没有太多了解。

我使用的是 Laravel 5.4。

最佳答案

从 Laravel 5.3 开始,您可以使用syncWithoutDetaching(最有效):

$this->followers()->syncWithoutDetaching([$user->id]);

其他方式:

$this->followers()->sync([$user->id], false);

保存前检查是否存在(仅当您已加载 $this->followers 时才有效):

function follow(User $user) {
if(!$this->followers->contains($user)) {
$this->followers()->attach($user->id);
}
}

关于mysql - 如何在关注或取消关注之前检查用户是否正在关注另一个用户(附件),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47835648/

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