laravel中实现无向图关系需同时定义friends和inversefriends双向关联,用with预加载或db union查询避免循环;递归连通性须用闭包表;渲染时需visited标记防重复。

在 Laravel 中实现无向图关系的嵌套查询,需将双向关联(如用户互为好友、节点相互连接)转化为可预加载、可递归遍历的结构,避免因方向模糊导致的重复加载或无限循环。
定义无向图模型关系
假设使用 User 模型表示图中节点,通过中间表 friends 表达无向边(user_id ↔ friend_id),迁移中已设联合唯一索引且无方向字段。
在 User 模型中不定义 hasMany('Friend') 这类单向关系,而是用 belongsToMany 显式声明对称关联:
public function friends() { return $this->belongsToMany(User::class, 'friends', 'user_id', 'friend_id'); }
同时添加反向访问器,让 $user->inverseFriends 实际查 friend_id = ? 的记录,确保双向路径可被 with() 预加载:
public function inverseFriends() { return $this->belongsToMany(User::class, 'friends', 'friend_id', 'user_id'); }
【必须同时定义 friends 和 inverseFriends 两个关系】 否则 with(['friends', 'inverseFriends']) 会漏掉一半连接,图结构断裂。
一次性加载指定深度的无向邻接子图
要获取某个用户及其所有“两跳内”的关联节点(即:本人 → 好友 → 好友的好友),不能靠链式 with('friends.friends'),那会只走单向路径且忽略 inverseFriends。
方法一:用嵌套预加载数组语法 + 手动合并集合
$user = User::with(['friends', 'inverseFriends'])->find($id);
$allNeighbors = $user->friends->merge($user->inverseFriends)->unique('id');
再对 $allNeighbors 循环预加载其 friends 和 inverseFriends,但注意去重和避免重复查询——这一步必须加缓存键或用 collect()->pluck('id') 构造 whereIn。
方法二(推荐):用 DB 查询构造器执行带 JOIN 的无向图展开
DB::table('users as u1')→join('friends as f1', 'u1.id', '=', 'f1.user_id')→join('users as u2', 'f1.friend_id', '=', 'u2.id')→where('u1.id', $id)→select('u2.*')→union( DB::table('users as u3')→join('friends as f2', 'u3.id', '=', 'f2.friend_id')→join('users as u4', 'f2.user_id', '=', 'u4.id')→where('u3.id', $id)→select('u4.*') )→get();
该写法显式覆盖 user_id→friend_id 和 friend_id→user_id 两种边方向,union 确保结果无重复,【union 前后两个子查询的 select 字段顺序和数量必须完全一致】,否则 MySQL 报错。
构建无向图的递归可达性查询
当需要判断 A 是否能通过任意条无向边到达 B(即连通分量判定),Eloquent 无法原生支持递归 CTE,必须退到查询构造器层。
第一步:创建临时闭包表(Closure Table)用于存储所有无向路径对
CREATE TABLE friend_closure ( ancestor BIGINT UNSIGNED NOT NULL, descendant BIGINT UNSIGNED NOT NULL, distance TINYINT UNSIGNED NOT NULL, PRIMARY KEY (ancestor, descendant), INDEX idx_descendant (descendant) );
第二步:用存储过程或 Artisan 命令填充该表,每次插入时同时写 (a,b,1) 和 (b,a,1),再递归扩展 distance=2、3… 直到无新增。
第三步:查询时直接 where ancestor = ? and descendant = ?,毫秒级返回是否连通。
这一步不可跳过——试图在运行时用 PHP 递归遍历 friends 关系会触发 N+1,1000 个节点就可能耗尽内存。
在 Blade 中安全渲染无向图层级结构
前端展示时,需防止同一节点在不同层级重复出现(例如 A 是 B 的好友,B 又是 C 的好友,A 在第二层再次出现)。
控制器中先生成带 visited 标记的扁平化路径数组:
$graph = []; $visited = []; $queue = [ ['node' => $startUser, 'depth' => 0] ]; while (!empty($queue)) { $current = array_shift($queue); if (in_array($current['node']->id, $visited)) continue; $visited[] = $current['node']->id; $graph[] = [ 'id' => $current['node']->id, 'depth' => $current['node']->depth, 'name' => $current['node']->name ]; foreach ($current['node']->friends as $friend) { if (!in_array($friend->id, $visited)) { $queue[] = [ 'node' => $friend, 'depth' => $current['depth'] + 1 ]; } } foreach ($current['node']->inverseFriends as $invFriend) { if (!in_array($invFriend->id, $visited)) { $queue[] = [ 'node' => $invFriend, 'depth' => $current['depth'] + 1 ]; } } }
Blade 中用 @foreach($graph as $item) 渲染即可,【$visited 必须是引用传递或全局数组,否则 in_array 判定失效】。











