7

如何在流式迁移中为非可选字段添加默认值?我目前有这个错误:

⚠️ PostgreSQL Error: column "firstName" contains null values

我唯一的选择是

public func field<T>(for key: KeyPath<Self.Model, T>, isIdentifier: Bool? = nil)
public func field<T>(for key: KeyPath<Self.Model, T>, type: Self.Model.Database.SchemaFieldType)

编辑:感谢蒂姆的回答,解决方案是:

static func prepare(on conn: PostgreSQLConnection) -> Future<Void> {
        return Database.update(User.self, on: conn) { builder in
            builder.field(for: \User.firstName, type: .text, .default(.literal("")))
        }
    }
4

2 回答 2

10

以防万一有人来到这里并试图在 Vapor 4 中做到这一点:

func prepare(on database: Database) -> EventLoopFuture<Void> {
    let defaultValue = SQLColumnConstraintAlgorithm.default(false)
    return database.schema(“event”)
        .field(“is_private”, .bool, .sql(defaultValue))
        .update()
}
于 2020-10-02T01:35:50.607 回答
7

您还没有看到另一个选项:

static func prepare(on connection: PostgreSQLConnection) -> Future<Void> {
  return Database.update(Event.self, on: connection) { builder in
    builder.field(for: \Event.isPrivate, type: .boolean, .default(.literal(.boolean(.false))))
  }
}
于 2019-08-27T19:24:11.450 回答