【问题标题】:Add Column to Existing Table in Vapor将列添加到 Vapor 中的现有表
【发布时间】:2019-03-24 18:00:55
【问题描述】:

我有一个正在处理的项目,其中包含 PostsComments。我使用外键 (postId) 将评论链接到帖子。但是,直到我第一次使用 Comment 类构建项目之后,这个外键才添加到我的 Comment 类中。

postId 字段添加到评论类后,我尝试运行项目并创建评论。该项目构建并运行良好,但是当我尝试创建评论时,出现错误:table Comment has no column named postId

这是 Vapor 中的某种迁移问题吗?

【问题讨论】:

    标签: swift sqlite vapor server-side-swift


    【解决方案1】:

    您仍然需要将您的数据库与您在 vapor 中的更改同步。如您所料,您可以通过配置迁移来做到这一点。将此添加到您的 configure.swift 文件中。如果您在选择其他名称之前已经创建了 Migration 结构,因为相同的名称可能会导致问题。

    struct AddPostID: Migration {
        // Need to declare which database, assuming PostgreSQL here
        typealias Database = PostgreSQLDatabase
    
        static func prepare(on conn: PostgreSQLConnection) -> Future<Void> {
            return Database.update(Comment.self, on: conn) { builder in
                builder.field(for: \.postId)
            }
        }
    
        static func revert(on connection: PostgreSQLConnection) -> Future<Void> {
            return Database.delete(Comment.self, on: connection)
        }
    }
    

    然后在同一个文件中将以下内容添加到您的 configure() 函数中(您可能已经有 MigrationConfig() 行和注册行,所以如果是这种情况,只需添加新行)

    var migrations = MigrationConfig()
    migrations.add(migration: AddPostID.self, database: .psql)
    services.register(migrations)
    

    【讨论】:

      猜你喜欢
      • 2016-11-13
      • 2023-04-07
      • 1970-01-01
      • 1970-01-01
      • 2016-07-04
      • 2017-04-29
      • 2020-12-19
      • 2018-02-21
      相关资源
      最近更新 更多