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

Laravel中如何基于User模型查询登录用户与目标用户的共同好友

实现方案

你可以直接在User模型中添加如下mutual方法,即可满足你预期的调用逻辑:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class User extends Model
{
    // 原有friends、friendsOf关联方法保留

    // 缓存共同好友查询结果,避免同一实例重复查询
    protected array $mutualFriends = [];

    /**
     * 查询当前用户和指定登录用户的共同好友
     * @param int $authUserId 登录用户ID
     * @return \Illuminate\Database\Eloquent\Collection
     */
    public function mutual(int $authUserId)
    {
        // 相同登录用户直接返回缓存结果
        if (isset($this->mutualFriends[$authUserId])) {
            return $this->mutualFriends[$authUserId];
        }

        return $this->mutualFriends[$authUserId] = $this->friends()
            ->whereExists(function ($query) use ($authUserId) {
                $query->select(DB::raw(1))
                    ->from('user_friends as auth_friends')
                    ->where('auth_friends.user_id', $authUserId)
                    ->whereRaw('auth_friends.user_friend_id = users.id');
            })
            ->get();
    }
}

逻辑说明

  • 直接通过SQL层面的whereExists查询,性能远高于先查全量好友再取集合交集的实现,好友量大的场景优势更明显
  • 新增了实例级缓存,如果你在同一个用户对象上多次调用mutual方法,只会执行一次查询
  • 完全适配你给出的双向存储好友关系的表结构,不需要修改原有关联逻辑
  • 调用方式和你预期的完全一致,返回的是共同好友的User模型集合,可以直接调用count()获取数量,遍历获取用户属性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 10:54:05