我有几个型号的日期字段的名称相同,如下所示:
final class ModelA: Model {
static let schema = "model_a"
@Timestamp(key: "modification_date", on: .update, format: .unix)
var modificationDate: Date?
}
final class ModelB: Model {
static let schema = "model_b"
@Timestamp(key: "modification_date", on: .update, format: .unix)
var modificationDate: Date?
}
final class ModelC: Model {
static let schema = "model_c"
@Timestamp(key: "modification_date", on: .update, format: .unix)
var modificationDate: Date?
}
在我的代码中的某个点上,我希望获得最近更改的模型.所以我可以写下这样的东西:
func getRecentlyChangedModelAs(on db: Database) async throws -> [ModelA] {
return try await ModelA.query(on: db)
.group(.and) { group in
group.filter(\.$modificationDate != nil)
group.filter(\.$modificationDate > Date.now.addingTimeInterval(TimeInterval(-3600)))
}
.all()
}
func getRecentlyChangedModelBs(on db: Database) async throws -> [ModelB] {
return try await ModelB.query(on: db)
.group(.and) { group in
group.filter(\.$modificationDate != nil)
group.filter(\.$modificationDate > Date.now.addingTimeInterval(TimeInterval(-3600)))
}
.all()
}
func getRecentlyChangedModelCs(on db: Database) async throws -> [ModelC] {
return try await ModelC.query(on: db)
.group(.and) { group in
group.filter(\.$modificationDate != nil)
group.filter(\.$modificationDate > Date.now.addingTimeInterval(TimeInterval(-3600)))
}
.all()
}
正如您所看到的,有很多代码重复.为了避免这种情况,我try 使用协议和通用查询:
protocol ModifiableModel: Model, Content {
var modificationDate: Date? { set get }
}
final class ModelA: ModifiableModel {
static let schema = "model_a"
@Timestamp(key: "modification_date", on: .update, format: .unix)
var modificationDate: Date?
}
etc...
func getRecentlyChangedModel<T: ModifiableModel>(on db: Database) async throws -> [T] {
return try await T.query(on: db)
.group(.and) { group in
group.filter(\.$modificationDate != nil) // Errors: 'nil' is not compatible with expected argument type 'KeyPath<Right, RightField>', Generic parameter 'RightField' could not be inferred
group.filter(\.$modificationDate > Date.now.addingTimeInterval(TimeInterval(-3600))) // Errors: Cannot convert value of type 'Date' to expected argument type 'KeyPath<Right, RightField>', No exact matches in call to instance method 'filter'
}
.all()
遗憾的是,这会在查询的过滤器中导致错误.我不太理解这些错误,但我发现没有过滤器,一切都编译得很好.我最好的猜测是,这些错误与我试图在筛选器中使用的关键路径有关.
有人知道问题出在哪里或如何解决吗?或者,有没有其他方法可以用来避免这种代码重复?任何帮助都将不胜感激!