user2239414
user2239414

Reputation: 33

Vapor Swift - Obtaining data from two Models

I have the next function on Vapor:

func getPartidosHandler(_ req: Request) throws -> Future<[PartidoWSData]> {
    return Partido.query(on: req).filter(\.estado == nil).all().map(to: [PartidoWSData].self) { partidos in
        var partidosWS: [PartidoWSData] = []
        for partido in partidos {

            // Something here

        }
        return partidosWS
    }
}

And the next struct PartidoWSData:

struct PartidoWSData: Content {
    let idPartido: String
    let fecha: String
    let sede1: Future<Sede>
    let sede2: Future<Sede>
}

My model Partido has two references to Sede, "sede1" and "sede2".

What I want is that the function gives an array of PartidoWSData struct, where I can see two properties of "Partido", "idPartido" and "fecha", and the two Sede related to the model.

How can I do that?

Thanks!

Upvotes: 1

Views: 209

Answers (1)

tanner0101
tanner0101

Reputation: 4065

I'm not sure exactly what type of relation exists between Partido and Sedebecause the model wasn't included here, but assuming it's a Parent/Child relation, you should be able to do something like:

func getPartidosHandler(_ req: Request) throws -> Future<[PartidoWSData]> {
    return Partido.query(on: req).filter(\.estado == nil).all().flatMap { partidos -> Future<[PartidoWSData]> in
        let partidoIDs = try partidos.map { try $0.requireID() }
        return Sede.query(on: req).filter(\.partidoID ~~ partidoIDs).map { sedes -> [PartidoWSData] in
            return partidos.map { partido -> PartidoWSData in
                return PartidoWSData(
                    id: partido.id
                    sedes: sedes.filter { $0.partidoID == partido.id }
                )
            }
        }
    }
}

The key is using the ~~ operator to do an x IN (...) predicate, following by using Array.filter to get the appropriate results.

Upvotes: 1

Related Questions