I have 3 tables, LastName, MiddleName and FirstName, I would like to create a new record or update record in FirstName, MiddleName only if lastName exists. if last name does not exist, then would like to return error back.
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
}
}
Fluent docs are very minimal on creating new record by doing nested joins,As ID's are auto generated when creating Lastname, how do I get the ID for creating MiddleName/FirstName. Also are there any good example of doing an update or create in multiple tables based on relationships?
Basically I want fluent to do something like
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