【发布时间】:2021-03-27 16:02:28
【问题描述】:
我有一个需要Decimal 类型的Fluent(支持Postgres)模型,但我只能存储.float/.double。
// Model
final class Stat: Model, Content, Equatable {
static let schema: String = "stats"
@ID(key: .id)
var id: UUID?
@Field(key: "name")
var name: String
@Field(key: "earned_run_average")
var era: Decimal // <-- CAN'T DO THIS
}
// Migration
struct CreateStatsTable: Migration {
func prepare(on database: Database) -> EventLoopFuture<Void> {
return database.schema(Stats.schema)
.id()
.field("name", .string, .required)
.field("earned_run_average", .decimal/*.decimal TYPE DOES NOT EXIST */, .required)
.create()
}
func revert(on database: Database) -> EventLoopFuture<Void> {
return database.schema(Stats.schema).delete()
}
}
上述带有迁移的模型将失败。如果这不容易实现(就像.string 或.double 一样简单),有没有办法在Fluent 中获得类似于Decimal 类型的行为?
【问题讨论】:
-
作为一种解决方法,尝试将其作为 .int 存储在模型中,使用此数据类型执行所有算术运算,然后创建一个 Int 扩展,以正确的精度报告它。
-
在迁移中将
Decimal用于您的era模型属性,将.string用于earned_run_average。
标签: postgresql vapor vapor-fluent