4

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

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

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

4

1 回答 1

6

您仍然需要将您的数据库与您在 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)
于 2019-02-07T01:39:34.267 回答