Search code examples
swiftpostgresqlforeign-keysfluentvapor

Add Foreign Key Constraint Swift Vapor Fluent with PostgreSQL


When I launch this command line vapor run prepare, I get the correct tables but the foreign key constraints are not added.

I have a Theme class and a Question class :

Theme: name, id

Question: title, id, theme_id

This is the prepare Database function in my Question class :

static func prepare(_ database: Database) throws {

        try database.create("questions") { questions in
            questions.id()
            questions.string("title")
            questions.parent(Theme.self, optional: false)
        }


    }

Solution

  • Foreign key constraints were added in Fluent 2:

    try database.create(self) { builder in
        builder.foreignKey("user_id", references: "id", on: User.self)
    }
    

    More info here:
    https://docs.vapor.codes/2.0/fluent/database/#foreign-keys