在 Vapor 迁移中添加默认值
Add a default value in migration in Vapor
如何在 Fluent 迁移中为非可选字段添加默认值?
我目前有这个错误:
⚠️ 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("")))
}
}
还有一个你没见过的选项:
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))))
}
}
以防万一有人来到这里并尝试在 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()
}
如何在 Fluent 迁移中为非可选字段添加默认值? 我目前有这个错误:
⚠️ 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("")))
}
}
还有一个你没见过的选项:
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))))
}
}
以防万一有人来到这里并尝试在 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()
}