根据问题的回答:vapor - 使用alsodecode() 从 mysql 获取数据我能够通过多个连接为我的模型重现此数据。
这导致了多个嵌套元组,我必须访问这些元组才能获得连接值。是否可以进行其他类型的连接或将此元组结构展平到一个级别?
struct MyTuple: Encodable, Content {
let title: String
let publicationDate: Date
let authorID: Author.ID
let authorName: String
let categoryID: Category.ID
let categoryName: String
let language: String
}
struct MyContext: Encodable {
let title: String
let books: [MyTuple]
}
func getBooks(_ req: Request) throws -> Future<[MyTuple]> {
return Book.query(on: req)
.join(\Category.id, to: \Book.categoryID)
.join(\Language.id, to: \Book.languageID)
.join(\ProgrammingLanguage.id, to: \Book.programmingLanguageID)
.join(\Author.id, to: \Book.authorID)
.alsoDecode(Category.self)
.alsoDecode(Language.self)
.alsoDecode(ProgrammingLanguage.self)
.alsoDecode(Author.self)
.sort(\Book.publicationDate, .descending).all().flatMap(to: [MyTuple].self) { tuples in
print(tuples)
var tempTuples: [MyTuple] = []
for tuple in tuples {
tempTuples.append(try MyTuple(
title: tuple.0.0.0.0.title,
publicationDate: tuple.0.0.0.0.publicationDate,
authorID: tuple.1.requireID(),
authorName: "\(tuple.1.name) \(tuple.1.surname)",
categoryID: tuple.0.0.0.1.requireID(),
categoryName: tuple.0.0.0.1.name, language: tuple.0.0.1.code ) )
}
return Future.map(on: req) {
tempTuples
}
}
}