我有 3 个表,LastName、MiddleName 和 FirstName ... FirstName 有 MiddleNameID 作为父级,MiddleName 有 LastName.id 作为父级
模型看起来像这样
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 DSL 进行多重连接?或者也许给我所有与中间名和/或姓氏匹配的名字
如果我不得不写一个 SQL 查询可能会是这样的
SELECT DISTINCT ON (ln.id, mn.id)
ln.name, mn.name, fn.*
FROM last_name ln
LEFT JOIN middle_name mn ON ln.id = mn.last_name_id
LEFT JOIN first_name fn ON fn.middle_name_id = mn.id
WHERE ( mn.name <> '' AND fn.name <> '' ) AND
(true AND ln.name ~ 'smith')
ORDER BY ln.id, mn.id, fn.id