蒸气3,使用来自另一个表的数据预填充表

时间:2019-05-09 08:26:24

标签: swift database postgresql vapor vapor-fluent

我正在尝试使用Vapor 3和Vapor fluent预先填充表格。我是蒸气新手

我正在尝试用Sharedkeys中的数据填充Platform。我设法查询了Platform。但是,我正在努力填充SharedKeys

所以每个platform都会有一个shared key

我在下面提供了一个示例,我没有运气。

在此行 let sharedKeys = platforms.map { platform in 我收到一个编译错误 Unable to infer complex closure return type: add explicit type to disambiguate

然后我意识到map返回[T],无法找到一种创建Future<SharedKey>而不是[SharedKey]的方法

这是我的编码示例,请随时批评!

平台模型

struct Platform : Codable {
    var id : Int?
    /// Type of platform, i.e. iPhone, iPad, Android etc...
    var platform : String

    init(platform : String) {
        self.platform = platform
    }
}

extension Platform : PostgreSQLModel, Content {}
extension Platform : PostgreSQLMigration {

    static func prepare(on conn: PostgreSQLConnection) -> Future<Void> {
        return Database.create(self, on: conn) { builder in
            try addProperties(to: builder)
            builder.unique(on: \.platform)
        }
    }
}

SharedKey模型

final class SharedKey: Codable {
    var id : Int?
    /// platform
    var platID : Platform.ID?
    /// shared key
    var key : String

    init(key: String, platform : Platform) {
        self.key    = key
        self.platID = platform.id
    }
}

extension SharedKey : PostgreSQLModel, Content {}
extension SharedKey : PostgreSQLMigration {

    static func prepare(on conn: PostgreSQLConnection) -> Future<Void> {
        return Database.create(self, on: conn) { builder in
            try addProperties(to: builder)
            builder.unique(on: \.key)
        }
    }
}

尝试填充sharedKey

        let p = Platform.query(on: conn).all()
        let keysFuture = p.flatMap(to: [SharedKey].self) { platforms in

            let sharedKeys = platforms.map { platform in
                let key = SharedKey(key: "<random key>", platform: platform)
                return key.save(on: conn)
            }

            return sharedKeys
        }


我期望变量keysFuture的类型为Future<[SharedKey]>,而不是[SharedKey]

编辑:

我已使用此示例预先填充Platformhttps://mihaelamj.github.io/Pre-populating%20a%20Database%20with%20Data%20in%20Vapor/

将字符串填充到表中很容易,但是尝试用shared key填充platform对我来说是一个挑战。

我意识到我需要Sharedkeys为[EventLoopFuture<Void>] 我确实更新了以下内容:

   let pp = Platform.query(on: conn).all()
        let op = pp.map { platforms in

           return platforms.map { p in
                return SharedKey(key: "random", platform: p).create(on: conn).map(to: Void.self) { _ in return }
            }
        }

但是,这返回为EventLoopFutrue<[EventLoopFutrue<Void>]>,有没有办法解开它?

我只需要从上面的链接(https://mihaelamj.github.io)中将[EventLoopFutrue<Void>]附加到futures

0 个答案:

没有答案
相关问题