You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何利用两列联合唯一特性优化WHERE子句的好友关系判断逻辑

好友关系校验方法优化方案

现有实现逻辑完全正确,核心可优化点是减少数据库查询次数:原实现最多会发起2次SQL查询,请求量大时会产生不必要的数据库负载,可通过OR条件合并两种匹配场景,仅执行1次查询即可得到结果。

优化后实现代码

public function isFriend($friend_id)
{
    $currentUserId = auth()->id();
    // 用闭包包裹两组条件避免逻辑优先级错误
    return Friend::where(function ($query) use ($currentUserId, $friend_id) {
        $query->where('user_id', $currentUserId)
              ->where('friend_id', $friend_id);
    })->orWhere(function ($query) use ($currentUserId, $friend_id) {
        $query->where('user_id', $friend_id)
              ->where('friend_id', $currentUserId);
    })->exists();
}

额外可选优化建议

  • 参数前置校验:提前判断传入的$friend_id是否等于当前登录用户ID、是否为合法数字ID,直接返回false避免无意义的数据库查询
  • 数据库索引优化:给friends表建立联合索引,可大幅提升该查询的执行速度,建索引SQL参考:
    CREATE INDEX idx_user_friend ON friends(user_id, friend_id);
    
  • 通用场景兼容调整:如果方法需要在非登录上下文调用,可以把当前用户ID改为可传参数,不要硬编码auth()->id():
    public function isFriend(int $userId, int $friendId): bool
    {
        return Friend::where(function ($query) use ($userId, $friendId) {
            $query->where('user_id', $userId)->where('friend_id', $friendId);
        })->orWhere(function ($query) use ($userId, $friendId) {
            $query->where('user_id', $friendId)->where('friend_id', $userId);
        })->exists();
    }
    
  • 缓存优化:如果好友关系变更频率不高,可以给查询结果加短期缓存,进一步降低数据库压力。

内容的提问来源于stack exchange,提问作者Junior Frogie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 15:57:03