2

我有 3 个表,LastName、MiddleName 和 FirstName,我想在 FirstName、MiddleName 中创建新记录或更新记录,前提是 lastName 存在。如果姓氏不存在,则想返回错误。


final class LastName: Model, Content {
    static let schema = "lastnames"
    
    @ID(key: .id)
    var id: UUID?

    @Field(key: "name")
    var name: String

    
    @Children(for: \.$lastname)
    var middle_names: [MiddleName]
    
    init() { }

    init(id: UUID? = nil, name: String) {
        self.id = id
        self.name = name
    }
}

final class MiddleName: Model, Content {
    static let schema = "middlenames"
    
    @ID(key: .id)
    var id: UUID?

    @Parent(key: "last_name_id")
    var lastname: LastName
    
    @Field(key: "name")
    var name: String

    @Children(for: \.$middleNameId)
    var firstNames: [FirstName]
    
    init() { }

    init(id: UUID? = nil, lastname: LastName, name: String ) {
        self.id = id
        self.lastname = lastname
        self.name = name
    }
}


final class FirstName: Model, Content {
    static let schema = "firstnames"
    
    @ID(key: .id)
    var id: UUID?
    
    @Parent(key: "middle_name_id")
    var middleNameId: MiddleName
    
    
    @Field(key: "name")
    var name: String
   
    
    init() { }

    init(id: UUID? = nil, middleNameId: MiddleName, name: String) {
        self.id = id
        self.middleNameId = testBundleId
        self.name = name
    }
}

流利的文档在通过嵌套连接创建新记录方面非常少,因为 ID 是在创建姓氏时自动生成的,我如何获取用于创建 MiddleName/FirstName 的 ID。还有任何基于关系在多个表中进行更新或创建的好例子吗?

基本上我想要流利地做类似的事情

 LastName.query(on: req.db).filter(\.$name == "Smith")
            .first()
            .unwrap(or: Abort(.notFound))
            // Now Find if middle name exists, if exists use the ID to create first name and maybe even update middle name table, 
            // if middle name does not exist, create middle name record, then use the new ID to create first name record
            // return the new record(s) as some new Swift Codable DTO
4

1 回答 1

3

你可以做类似的事情

LastName.query(on: req.db).filter(\.$name == "Smith")
  .first()
  .unwrap(or: Abort(.notFound))
  .flatMap { lastName in
    let middlenameQuery = MiddleName.query(on: req.db).filter(\.$name == "Jane").first().flatMap { middlenameFound in
      if let middleName = middlenameFound {
        return req.eventLoop.future(middleName)
      } else {
        let newMiddlename = Middlename(name: "Jane")
        return newMiddlename.create(on: req.db).transform(to: newMiddlename)
      }
    }
    return middlenameQuery.flatMap { middlename in
      // Use last name and middle name here
    }

}
于 2021-06-01T15:39:48.363 回答