Hugo Patural
Hugo Patural

Reputation: 75

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


    }

Upvotes: 4

Views: 1690

Answers (2)

tanner0101
tanner0101

Reputation: 4065

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

Upvotes: 3

Philip Pegden
Philip Pegden

Reputation: 2164

Also, one can add a raw SQL statement during the preparation, which can get you out of most situations. For example one could add this additional line to create a unique constraint across multiple columns.

questions.raw("UNIQUE (pararent_id, title)")

But serves many purposes...

Upvotes: 1

Related Questions