【问题标题】:Creating data in SQLite database manually in Vapor在 Vapor 中手动创建 SQLite 数据库中的数据
【发布时间】:2019-05-21 20:41:38
【问题描述】:

如何在 Vapor 项目中手动向 SQLite 数据库添加数据,以便在启动时已经有一些数据?

【问题讨论】:

  • 你到底是什么意思,因为听起来你已经回答了你自己的问题,你通过手动添加数据来手动添加数据。我知道这不是你的意思,所以请澄清一下。
  • 我的意思是以编程方式将对象添加到数据库中,我没有找到解决方案。

标签: swift sqlite vapor server-side-swift


【解决方案1】:

我用这个:

struct CreateAdminUser: Migration {

    static func prepare(on connection: SQLiteConnection) -> Future<Void> {
        let password = try? BCrypt.hash("secret")
        let user = User(email: "me@example.co.uk", password: password!)
        return user.save(on: connection).transform(to: ())
    }

    static func revert(on connection: SQLiteConnection) -> Future<Void> {
        return Future.map(on: connection) {}
    }
}

然后我将此行放入configure.swift迁移:

migrations.add(migration: CreateAdminUser.self, database: .sqlite)

【讨论】:

    猜你喜欢
    • 2023-04-03
    • 2013-02-03
    • 2019-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-26
    • 2014-04-07
    • 1970-01-01
    相关资源
    最近更新 更多