vapor/fluent-mysql-driver

Database create table without foreign keys

Nexmind opened this issue · 1 comments

Hello,

I follow the official Vapor doc about MySQLFluent Vapor V3 doc but when my tables are created i've no foreign key in my database, and unfortunately if found nothing in the doc or already open/closed issue about that.

Here's my parent model:

final class Teacher: Model {
    typealias Database = MySQLDatabase
    
    typealias ID = Int
    static var idKey: WritableKeyPath<Teacher, Int?> = \.id
    var id: Int?
    
    var name: String
    var email: String

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

extension Teacher {
    var schoolClass: Children<Teacher, SchoolClass> {
        return children(\.idTeacher)
    }
}

And here is the child model

final class SchoolClass: Model {
    typealias Database = MySQLDatabase
    
    typealias ID = Int
    static var idKey: WritableKeyPath<SchoolClass, Int?> = \.id
    var id: Int?
    
    var level: Int
    var letter: String
    var idTeacher: Teacher.ID
    
    init(id: Int?, level: Int, letter: String, idTeacher: Int) {
        self.id = id
        self.level = level
        self.letter = letter
        self.idTeacher = idTeacher
    }
}

extension SchoolClass {
    var teacher: Parent<SchoolClass, Teacher> {
        return parent(\.idTeacher)
    }
}

Did i miss something in the doc or comprehension, or should i prepare a specific method to create manually foreign key ?

Thanks !

Ok i figured out the prepare method in the migration protocol, and this solve my problem.

extension SchoolClass: Migration {
    static func prepare(on conn: MySQLConnection) -> Future<Void> {
        return Database.create(self, on: conn, closure: { builder in
            try self.addProperties(to: builder)
            builder.reference(from: \.idTeacher, to: \Teacher.id)
        })
    }
}