首页 > 解决方案 > 为相互关注的用户建立雄辩的关系

问题描述

我有一个像 Instagram 这样的应用程序,用户可以在其中互相关注,所以我把它放在我的用户模型中:

    public function following()
{
    return $this->belongsToMany(User::class, 'follow_rel', 'follower_id', 'followed_id');
}

public function followers()
{
    return $this->belongsToMany(User::class, 'follow_rel', 'followed_id', 'follower_id');
}

public function follow(User $user)
{
    $this->following()->syncWithoutDetaching($user);
}

public function unfollow(User $user)
{
    $this->following()->detach($user);
}

这是我的迁移:

        Schema::create('follow_rel', function (Blueprint $table) {
        $table->increments('id');
        $table->boolean('accepted')->default(false);
        $table->unsignedInteger('follower_id');
        $table->unsignedInteger('followed_id');
        $table->timestamps();
    });

它工作正常,但我不知道如何处理“接受”列。就像 Instagram 一样,我希望第一个用户发送请求,如果第二个用户的帐户是私有的,则将接受的列设置为 false,所以当我编写查询以获取 follow_relations 时,跳过那些不被接受的(就像软删除一样)。我应该如何修改我的关系来实现这一点?或者我应该创建另一个名为“requst_rel”的表并在接受后将其移动到“follow_rel”表?任何帮助将不胜感激谢谢

标签: mysqllaraveleloquent

解决方案


我不完全确定我理解,但听起来你想查询只被接受的关系?如果是这样,您想使用以下wherePivot方法:

$followers = $user->followers()-> wherePivot('accepted', true)->get();

或者你可以在模型上创建一个方法:

public function accepted_followers()
{
    return $this->belongsToMany(User::class, 'follow_rel', 'followed_id', 'follower_id')->wherePivot('accepted', true);
}

$followers = $user->accepted_followers;

推荐阅读