G. Marc
G. Marc

Reputation: 5997

How to save a model with a specific id in Vapor 3

I'm trying to add some seed data to a table in a migration. For this table I don't want the id value to be generated automatically, but I want to set it manually for each record. How can this be done? My current code looks like the bellow, but the record isn't inserted to the database and no error is thrown when the migration runs.

Model class:

import Foundation
import FluentPostgreSQL
import Vapor

final class PropertyType: PostgreSQLModel {
    var id: Int?
    var name: String

    init(id: Int, name: String) {
        self.id = id
        self.name = name
    }
}

extension PropertyType: Migration { }
extension PropertyType: Content { }
extension PropertyType: Parameter { }

Migration class:

import FluentPostgreSQL
import Vapor

struct AddPropertyTypes: Migration {
    typealias Database = PostgreSQLDatabase

    static func prepare(on conn: PostgreSQLConnection) -> Future<Void> {
        let propertyType1 = PropertyType(id: 1, name: "Einfamilienhaus")
        return propertyType.save(on: conn).transform(to: ())
    }

    static func revert(on conn: PostgreSQLConnection) -> Future<Void> {
        let futures = [1].map { id in
            return CodePropertyType.query(on: conn).filter(\CodePropertyType.id == id)
                .delete()
        }
        return futures.flatten(on: conn)
    }
}

Upvotes: 1

Views: 218

Answers (1)

imike
imike

Reputation: 5656

Just replace

propertyType.save(on: conn)

with

propertyType.create(on: conn)

Upvotes: 2

Related Questions