【问题标题】:How to store a Vapor Fluent model with decimal field如何存储带有小数字段的 Vapor Fluent 模型
【发布时间】: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


【解决方案1】:

Proper Decimal support for Postgres是最近添加的。

因此,您应该能够在 Model 中使用 Decimal 对 Postgres DB 中的 Decimal 值进行编码/解码,而不会出现任何问题。

至于Migration,仍然没有.decimal DataType,因此您可以简单地为Postgres 数据库使用自定义字段,例如numeric

.field("earned_run_average", .sql(raw: "NUMERIC(7,2)"), .required)

这应该让您可以毫无问题地使用Decimal

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-10
    • 2019-06-20
    • 2021-11-08
    • 2022-01-01
    • 1970-01-01
    • 2022-01-08
    • 2018-11-27
    • 2020-08-19
    相关资源
    最近更新 更多