postgresql - 如何使用 Fluent 从 Vapor 3 中的同一个表中进行两个 JOIN 查询?
问题描述
这就是我想要做的(使用 postgresql):
选择 H."name", A."name"
来自“匹配”M
加入“团队”H ON M.“homeTeamID”= 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)
这是错误:
{
错误:是的,
原因:“表名“团队”指定了多次”
}
任何帮助表示赞赏!谢谢!
解决方案
@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
}
}
}
推荐阅读
- android - 如何在 viewpaper 中仅添加按钮?
- javascript - 用Javascript生成随机足球比赛的算法
- javascript - 合并来自 Promise.all 和 map 的数组结果
- dynamic-programming - 返回从商店购买物品的最大奖励
- http - 这是通过使用所有非 5xx http 状态代码/所有状态代码来计算网站可用性的正确方法吗?
- c++ - 将谷物构建为 .dll
- javascript - 上传更大图像时的引导程序问题
- python - 无法访问元组中的元素
- python - 在 python 中引用 .props 文件的节点
- jestjs - jasmine.createSpyObj() 的等价物是什么?