Adding Foreign Keys to a Database in Vapor

Foreign key constraints describe a link between two tables.


final class Technique: Codable {
  var id : Int?
  let name : String
  var description: String
  var heatID: Heat.ID
  init(name: String, description: String, heatID: Heat.ID) { = name
    self.description = description
    self.heatID = heatID

Here the Technique model needs a Heat ID.

To add referential integrity, we need to conform to Migrations protocol:

extension Technique : Migration {
  static func prepare(on connection: PostgreSQLConnection) -> Future<Void> {
    return Database.create(self, on: connection) { builder in
      try addProperties(to: builder)
      // Add FOREIGN KEY reference, with ON UPDATE/DELETE CASCADE actions
      try builder.addReference(from: \.heatID, to: \, actions: .update)
      // make name UNIQUE and indexed
      try builder.addIndex(to: \.name, isUnique: true)

In the above example the relationship is one - to - many between Heat and Technique.

Heat ↤⇉ Technique

And many - to - one between Technique and Heat.

Technique ⇇↦ Heat

Prev: Adding Indexes and Constraints to a Database in Vapor

Next: Pre-populating a Database with Data in Vapor

Vapor 3 Tutorial Start

#pub #db #postgresql #vapor #swift #ddl #one-to-many #many-to-one #migration