简体   繁体   English

Vapor - 流畅,保存object到PostgreSQL

[英]Vapor - fluent, save object to PostgreSQL

Could someone give me example please, how to save Object to DB?有人可以给我举个例子吗,如何将 Object 保存到数据库? For example, I am using a GET request which triggers the HTML parser and returns user a model. How I can save that model to my DB?例如,我正在使用触发 HTML 解析器并向用户返回 model 的GET请求。如何将 model 保存到我的数据库中?

func parseHTML() -> ModelObject{
    
}

app.get("getData") { req -> [ModelObject] in
    let controller = TestController()
    let data = controller.parseHTML()
            
    //Save data to DB
    return data
}

The standard way of doing this is to add these lines to create the record in the database:这样做的标准方法是添加这些行以在数据库中创建记录:

app.get("getData") { req -> [ModelObject] in
    let controller = TestController()
    let data = controller.parseHTML()

    // update fields in the controller instances with values from your decoded form
    controller.field = data.field

    return controller.create(on: database).flatMap { _ in
        //return controller
        return data
    }
}

create returns a future Void , but the instance of the model in controller has been updated to include the primary key (assuming it is auto-generated) so you can just return this, although I have left your original return of the decoded form data. create返回一个未来的Void ,但是 controller 中的controller的实例已经更新为包含主键(假设它是自动生成的)所以你可以只返回它,尽管我已经离开了你原来的解码表单数据的返回。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM