BlondeSwan
BlondeSwan

Reputation: 782

Add Column to Existing Table in Vapor

I have a project that I am working on that has Posts and Comments. I link a comment to a post using a foreign key (postId). However, this foreign key was not added to my Comment class until after the first time I had built the project with the Comment class.

After adding the postId field to the comment class, I attempted to run the project and create a comment. The project builds and runs fine, but when I attempt to create a comment, I get the error: table Comment has no column named postId

Is this some sort of migration issue within Vapor?

Upvotes: 5

Views: 1115

Answers (1)

Lena Evans
Lena Evans

Reputation: 71

You still need to sync your database with your changes in vapor. As you guessed, you can do this by configuring a migration. Add this to your configure.swift file. If you've already made a Migration struct before you may want to choose a different name as the same name can cause issues.

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)
    }
}

Then add the following to your configure() function in the same file (you may already have the MigrationConfig() line and register line so just add the new line if that's the case)

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

Upvotes: 7

Related Questions