我已经梳理了这里的文档,但我不太清楚如何更新关系和模型(例如,关系发生了变化,属性发生了变化)。解码后 ModelA 中的“childrenArray”似乎为空,但是,我无法确定,因为在尝试打印值时出现此错误:
致命错误:子关系未急切加载,使用 $ 前缀访问
我的父模型:
final class ModelA: Model, Content {
static let schema = "model_a"
// MARK: - PROPERTIES
@ID(key: .id)
var id: UUID?
@Field(key: "name")
var name: String
// MARK: - RELATIONS
@Children(for: \.$modelA)
var childrenArray: [ModelB]
init() { }
init(id: UUID? = nil, name: String) {
self.id = id
self.name = name
}
}
儿童模型:
final class ModelB: Model, Content {
static let schema = "model_b"
// MARK: - Properties
@ID(key: .id)
var id: UUID?
@Field(key: "command")
var command: String
// MARK: - Relations
@Parent(key: "model_a_id")
var modelA: ModelA
}
我的更新功能:
func update(req: Request) throws -> EventLoopFuture<ModelA> {
guard let id = req.parameters.get("id", as: UUID.self) else {
throw Abort(.internalServerError)
}
let updatedModelA = try req.content.decode(ModelA.self)
return ModelA.find(id, on: req.db)
.unwrap(or: Abort(.notFound))
.flatMap { modelA in
modelA.$childrenArray.create(updatedModelA.childrenArray, on: req.db)
return modelA.update(on: req.db).map { modelA }
}
}
作为参考,PostmanPOST
请求如下所示:
{
"id": "<ModelA's UUID>",
"name": "ModelA Name",
"childrenArray": [{
"id": "{{$randomUUID}}" ,
"command": ""
}]
}