Laravel - 检查用户是否已被关注

时间:2017-05-15 11:20:38

标签: php laravel

我想检查用户是否已经关注了其他用户,

在我的数据库中我有:

user_id     follow_id   
1               2
1               3
1               4
1               5

现在假设用户1没有关注用户6,我该如何检查? 或者我如何检查用户是否已被关注?

1 个答案:

答案 0 :(得分:0)

如果你正在使用雄辩的话,你可以这样做。

// Add these to your User model
public function following()
{
    return $this->belongsToMany(User::class, 'follows', 'user_id', 'follow_id')->withTimestamps();
}

public function followers()
{
    return $this->belongsToMany(User::class, 'follows', 'follow_id', 'user_id')->withTimestamps();
}

public function isFollowing(User $user)
{
    return !! $this->following()->where('follow_id', $user->id)->count();
}

public function isFollowedBy(User $user)
{
    return !! $this->followers()->where('user_id', $user->id)->count();
}

// Make the check
$user = User::findOfFail(1);
$checkUser = User::findOfFail(6);

if ($user->isFollowing($checkUser)) {
    // Following
} else {
    // Not following
}

这也使得它可以关注和取消关注用户。如果您想要完整实现示例,请查看以下链接。

https://github.com/gothinkster/laravel-realworld-example-app/blob/master/app/RealWorld/Follow/Followable.php