vapor - Obtaining data from mysql using alsodecode()

怎甘沉沦 提交于 2021-02-10 15:59:24

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!