mysql - 为相互关注的用户建立雄辩的关系
问题描述
我有一个像 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”表?任何帮助将不胜感激谢谢
解决方案
我不完全确定我理解,但听起来你想查询只被接受的关系?如果是这样,您想使用以下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;
推荐阅读
- python - 通过 SSH 和 SQLAlchemy 将 Python 连接到 Redshift
- javascript - 如何用棱镜2在银行中插入关系数据
- php - 如何在 Laravel Eloquent 中获取不在集合中的项目?
- javascript - 带有 geoJson 的传单插件
- mysql - 匹配两个 MySQL 表中的一个键并返回一个具有最大值的键
- javascript - 嵌套元素鼠标悬停,如何不重复孩子
- azure - 如何将 Office365 Exchange 与我的 Azure Portal AD 连接/同步?
- c++ - C++:使用“auto”在二维数组上嵌套 For 循环
- angular - Angular 9 - 指令,如何从组件中读取属性
- git - 关于通过 SSH 和 GitHub 上的现有存储库部署到实时 Web 服务器的建议