2

我已经梳理了这里的文档,但我不太清楚如何更新关系和模型(例如,关系发生了变化,属性发生了变化)。解码后 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": ""
    }]
}
4

1 回答 1

2

要完成“急切加载”,您需要with在父查询中包含一个。您不能使用 a 执行此操作,find因此您需要将查询更改为:

ModelA.query(on: req.db)
    .filter(\.$id == id)
    .with(\.$childrenArray)
    .first()
    .unwrap(or: Abort(.notFound))
    .flatMap { modelA in
        // can access children now
        return modelA.update(on: req.db).map { modelA }
    }

我假设您希望此行在 ModelB 中创建子代:

modelA.$childrenArray.create(updatedModelA.childrenArray, on: req.db)

它不会。您需要创建 的新实例ModelB,初始化父属性,然后调用create.

于 2021-03-20T16:58:15.173 回答