Swift Vapor:通过迁移同时从结构中删除数据库字段

Swift Vapor: remove database field via migration and from struct at the same time

我添加了一个数据库迁移来删除一个字段:

static func prepare(on conn: PostgreSQLConnection) -> EventLoopFuture<Void> {
    return Database.update(User.self, on: conn) { builder in
        builder.deleteField(for: \.name)
    }
}

现在这工作正常,除了当我从我的 User 结构中删除字段 name 时,它不再编译,因为显然 name 的键路径不能'找不到。
因此,这需要我将字段保留在 User 结构中,直到迁移具有 运行 之后,然后我可以删除该字段,但我还需要删除迁移。

我觉得这不是一个好的做法,我可能做错了什么。
我可以做什么?

您可以按名称获取字段并将其删除:

builder.deleteField(User.Database.QueryField.column("users", "name"))

哪里

  • users 是 table 名字
  • name 是 column/field 名字

这是一个完整的迁移,显示添加了一个字段,然后还原以将其删除:

    struct UpdateUserTable1: Migration {
        func prepare(on database: Database) -> EventLoopFuture<Void> {
            database.schema("User")
                .field("nextAttemptAt", .datetime)
                .update()
        }

        func revert(on database: Database) -> EventLoopFuture<Void> {
            database.schema("User")
                .deleteField("nextAttemptAt")
                .update()
        }
    }

如您所见,迁移不需要在模型中定义字段,也不需要在任何阶段定义字段。这是使用 Fluent 的正确方法。