简体   繁体   English

Vapor 2,Fluent 模型子类

[英]Vapor 2, Fluent model subclass

I'm using Vapor 2 and trying to create non-final model to subclass it.我正在使用 Vapor 2 并尝试创建非最终模型来对其进行子类化。 Is it possible?是否可以? I have following code for abstract model:我有以下抽象模型代码:

class MongoObject: Model, JSONRepresentable {

    let storage = Storage()

    let creationDate: Date

    init() {
        creationDate = Date()
    }

    required init(row: Row) throws {
        creationDate = try row.get(KeyPath.creationDate)
    }

    func makeRow() throws -> Row {
        var row = Row()
        try row.set(KeyPath.creationDate, creationDate)
        return row
    }

    func makeJSON() throws -> JSON {
        var json = JSON()
        try json.set(KeyPath.id, id)
        try json.set(KeyPath.creationDate, creationDate)
        return json
    }

}

extension MongoObject: Preparation {

    class func prepare(model: Creator) { }

    static func prepare(_ database: Database) throws {
        try database.create(self) { (builder) in
            builder.id()
            builder.date(KeyPath.creationDate)
            prepare(model: builder)
        }
    }

    static func revert(_ database: Database) throws {
        try database.delete(self)
    }

}

but got compilation error:但得到编译错误:

method 'make(for:)' in non-final class 'MongoObject' must return Self to conform to protocol 'Parameterizable'非最终类“MongoObject”中的方法“make(for:)”必须返回Self以符合协议“Parameterizable”

Your non-final "abstract" model with subclasses is conforming to Parameterizable as part of the Model conformance.您的非最终“抽象”模型与子类符合Parameterizable作为Model一致性的一部分。 Parameterizable requires returning Self . Parameterizable 需要返回Self By default this is implemented by reading the entity's id from the path component.默认情况下,这是通过从路径组件读取实体的 id 来实现的。 The problem you now get is that the compiler can't return Self for subclasses since it's implemented on a higher model.您现在遇到的问题是编译器无法为子类返回Self ,因为它是在更高的模型上实现的。

The solution is pretty straightforward, you cannot do subclassing here.解决方案非常简单,您不能在这里进行子类化。

I might be too late, but I was having the exact same problem and all I had to do was make the class final.我可能为时已晚,但我遇到了完全相同的问题,我所要做的就是让课程成为决赛。

method 'make(for:)' in non-final class 'MongoObject' must return Self to conform to protocol 'Parameterizable'非最终类“MongoObject”中的方法“make(for:)”必须返回 Self 以符合协议“Parameterizable”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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