如何使用Fluent从Vapor 3中的同一表中执行两个JOIN查询?



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

选择 H。名字",A。名字">

来自"火柴"M

加入"团队"H on M。主页团队 ID" = H.id

加入"团队"A on M。离开团队 ID" = 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)

这是错误:

{

错误:真,

原因:"表名"团队"指定了多次">

}

任何帮助不胜感激!谢谢!

@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
}
}
}

我在这里创建了一个测试项目: https://github.com/mixio/multi-join-test

欣赏现在这是一个老问题,但我遇到了类似的问题,我通过使用原始SQL查询用另一种方法解决了它。

下面将为主队和客队名称添加其他列。您需要创建一个 MatchObject 来解码结果,并根据您的情况建立连接。

func matchObjects(_ req: Request) throws -> Future<[MatchObject]> {
return req.withPooledConnection(to: .psql, closure: { conn in
return conn.raw("""
SELECT "Matches".*, h.name as home_team_name, a.name as away_team_name
FROM "Matches"
INNER JOIN "Teams" as h ON "Matches"."homeTeamID" = h.id
INNER JOIN "Teams" as a ON "Matches"."awayTeamID" = a.id
""").all(decoding: MatchObject.self)
})
}

最新更新