vapor / fluent-mysql-driver

šŸ–‹šŸ¬ Swift ORM (queries, models, relations, etc) built on MySQL.
MIT License
78 stars 52 forks source link

vapor 3 mysql join query and decode fields #142

Closed wenxini234 closed 5 years ago

wenxini234 commented 5 years ago
final class Service: MySQLModel {
    var id: Int?
    var sername: String?
    var orgid:String?
}

final class Users: MySQLModel {
    var id: Int?
    var orgid: String?
    var type:String?
}

struct ResponseJSON<T: Content>: Content {
    private var code: Int
    private var message: String
    private var data: T?

    init(code: Int = 0,
         message: String,
         data:T?) throws {
        self.code = code
        self.message = message
        self.data = data
    }

    init(code: Int = 0,
         message: String) throws {
        self.code = code
        self.message = message
        self.data = nil
    }
}

func list(_ req: Request) throws -> Future<Response> {
    return Service.query(on: req)
        .join(\Users.orgid,to: \Service.orgid)
       //.alsoDecode(Users.self)
        .range(lower: 0, upper: 2)
        .all()
        .flatMap({ content in
                        return try ResponseJSON<[Service]>(code: 0, message: "success",data:content).encode(for: req)
        })
}

I want to get all the field information of the two tables, put it in data, and finally return to json, eg:

{
    message::"success",
        data: [{
                id: 1,
                type: "free",
                orgid: "org1",
                sername: "ser1"
            },
            {
                id: 2,
                type: "free",
                orgid: "org2",
                sername: "ser2"
            }
        ],
        code: 0
}
tanner0101 commented 5 years ago

Hi @wenxini234, check out this example:

struct GalaxyWithPlanet {
    var id: Int
    var name: String
    var planet: Planet
}
func index(_ req: HTTPRequest) -> EventLoopFuture<[GalaxyWithPlanet]> {
    return self.db.query(Galaxy.self).join(\Planet.galaxyID, to: \.id).alsoDecode(Planet.self).all().map { res in
        return try res.map { (galaxy, planet) in
            return try GalaxyPlanet(id: galaxy.requireID(), name: galaxy.name, planet: planet)
        }
    }
}