简体   繁体   中英

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


    }

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

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...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM