Could someone give me example please, how to save Object to DB?
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?
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.