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

Vapor/Fluent嵌套请求过滤:如何筛选tournamentGames返回的指定玩家Game数据

正确实现代码

你需要调整tournamentGames关联下的过滤字段,示例写法如下:

// 提前提取用户ID,避免多层闭包的隐式引用风险
let targetUserId = user.id!

let uQuery = User.query(on: req.db)
    .filter(\.$id == targetUserId)
    .with(\.$playerTournaments) { tournament in
        tournament.with(\.$tournamentGames) { game in
            // 过滤Game的$player关联ID等于当前用户ID
            game.filter(\.$player.$id == targetUserId)
        }
    }
    .all()

关键修改说明

  • 你之前的写法错误过滤了Game自身的ID,实际需要过滤Game对象的$player关联属性对应的外键,Fluent中对@Parent关联的外键过滤需要使用\.$player.$id的投影写法
  • 提前提取用户ID变量可以避免多层闭包内直接解包user可能带来的编译错误或引用问题

可选优化:过滤无匹配Game的赛事

如果某个赛事下没有属于当前用户的Game,上述写法会返回tournamentGames为空数组的赛事对象。如果需要直接过滤掉这部分无关联Game的赛事,可以调整为如下写法:

let targetUserId = user.id!

let uQuery = User.query(on: req.db)
    .filter(\.$id == targetUserId)
    .with(\.$playerTournaments) { tournament in
        tournament
            .join(Game.self, on: \Tournament.$id == \Game.$tournament.$id)
            .filter(Game.self, \.$player.$id == targetUserId)
            .with(\.$tournamentGames) { game in
                game.filter(\.$player.$id == targetUserId)
            }
    }
    .all()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 05:06:01