问题
I'm trying to obtain data from a mysql database joining two of my tables (usuarios and colegios) with the function alsodecode().
My code looks like this:
func usuariosHandler(_ req: Request) throws -> Future<View> {
return Usuario.query(on: req).join(\Colegio.id, to: \Usuario.colegioId).alsoDecode(Colegio.self).all().flatMap(to: View.self) { usuarios in
let contexto = UsuariosContext(title: "Usuarios de la aplicación", usuarios: usuarios)
return try req.view().render("usuarios", contexto)
}
}
The problem is that the result of the query is a tuple that I have to send to a view through leaf. In addition, this is the error into the compiler: Cannot convert value of type '[(Usuario, Colegio)]' to expected argument type '[Usuario]'
I'm a beginner of Swift and Vapor. Can anybody help me with this?
Thanks!
回答1:
You need to use an Encodable
structure to pass tuples - one structure to hold the tuple data and one for the context:
struct MyTuple: Encodable {
let name: String // put the fields from the join in here
}
struct MyContext Encodable {
let title: String
let usuarios: [MyTuple]
}
Then modify your route to create the data structure to pass as the context:
func usuariosHandler(_ req: Request) throws -> Future<View> {
return Usuario.query(on: req).join(\Colegio.id, to: \Usuario.colegioId).alsoDecode(Colegio.self).all().flatMap(to: View.self) { usuarios in
var usuariosTuples: [MyTuple] = []
for usuario in usuarios {
usuariosTuples.append( MyTuple( usuario.0 ) )
}
let contexto = UsuariosContext(title: "Usuarios de la aplicación", usuarios: usuariosTuples)
return try req.view().render("usuarios", contexto)
}
}
I've assumed the first field is a string
.
来源:https://stackoverflow.com/questions/51484138/vapor-obtaining-data-from-mysql-using-alsodecode