首页 > 解决方案 > 如何使用 Fluent 从 Vapor 3 中的同一个表中进行两个 JOIN 查询?

问题描述

这就是我想要做的(使用 postgresql):

选择 H."name", A."name"

来自“匹配”M

加入“团队”H ON M.“h​​omeTeamID”= H.id

JOIN "Teams" A ON M."awayTeamID" = A.id

//This will give me an error

return Matches.query(on: request)
.join(\Teams.id, to: \Matches.homeTeamID)
.alsoDecode(Teams.self)
.join(\Teams.id, to: \Matches.awayTeamID)
.alsoDecode(Teams.self)

这是错误:

{

错误:是的,

原因:“表名“团队”指定了多次”

}

任何帮助表示赞赏!谢谢!

标签: postgresqlfluentvapor

解决方案


@arema,我试图重现您的用例,并且在 Fluent 中遇到了类似的问题。我在 Fluent 的 github 上报告了这个问题: https ://github.com/vapor/fluent/issues/563

这是一种解决方法,但它远非优雅。

// Requires conforming `Match` to hashable, Equatable.
func getMatches2Handler(_ req: Request) throws -> Future<[MatchObjects]> {
    return map(
        to: [MatchObjects].self,
        Match.query(on: req).join(\Team.id, to: \Match.homeTeamID).alsoDecode(Team.self).all(),
        Match.query(on: req).join(\Team.id, to: \Match.awayTeamID).alsoDecode(Team.self).all()
    ) { homeTuples, awayTuples in
        let homeDictionary = homeTuples.toDictionary()
        let awayDictionary = awayTuples.toDictionary()
        var matchObjectsArray: [MatchObjects] = []
        matchObjectsArray.reserveCapacity(homeDictionary.count)
        for (match, homeTeam) in homeDictionary {
            let awayTeam = awayDictionary[match]!
            matchObjectsArray.append(MatchObjects(match: match, homeTeam: homeTeam, awayTeam: awayTeam))
        }
        return matchObjectsArray
    }
}

//...

extension Array {
    func toDictionary<K,V>() -> [K:V] where Iterator.Element == (K,V) {
        return self.reduce([:]) {
            var dict:[K:V] = $0
            dict[$1.0] = $1.1
            return dict
        }
    }
}

推荐阅读