user2239414
user2239414

Reputation: 33

vapor - Obtaining data from mysql using alsodecode()

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!

Upvotes: 1

Views: 231

Answers (1)

Nick
Nick

Reputation: 5180

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.

Upvotes: 1

Related Questions