[英]Vapor Fluent How to add a new required field key to existing table
I have a deployed backend built with Vapor Fluent PostgreSQL.我有一个使用 Vapor Fluent PostgreSQL 构建的已部署后端。
Now I need to add a new required field key new_field
to the table with schema name schema_name
in the database.现在我需要在数据库中使用模式名称
schema_name
向表中添加一个新的必填字段键new_field
。 I created a new migration:我创建了一个新的迁移:
struct AddNewFieldToSchema: Migration {
func prepare(on database: Database) -> EventLoopFuture<Void> {
database.schema("schema_name")
.field("new_field", .string, .required)
.update()
}
func revert(on database: Database) -> EventLoopFuture<Void> {
database.schema("schema_name")
.deleteField("new_field")
.update()
}
}
But after running, it gives me error:但运行后,它给了我错误:
Fatal error: Error raised at top level: server: column "new_field" of relation "schema_name" contains null values (ATRewriteTable)
I am guessing it is because there are existing data created using old data model that does not have values for new_field
, because this new migration runs fine if the database is empty.我猜这是因为使用旧数据 model 创建的现有数据没有
new_field
的值,因为如果数据库为空,则此新迁移运行良好。
How do I fix this issue?我该如何解决这个问题? Thanks.
谢谢。
The .field
function takes a list of optional properties where you can pass a default, so for you it would be .field
function 采用可选属性列表,您可以在其中传递默认值,因此对您来说
func prepare(on database: Database) -> EventLoopFuture<Void> {
database.schema("schema_name")
.field("new_field", .string, .required, .sql(.default("Your default value")))
.update()
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.