swift - 将我的 Fluent 模型链接到预先存在的数据库表

标签 swift postgresql vapor server-side-swift vapor-fluent

我一直在尝试将我的 PostgreSQL 数据库链接到 Swift Vapor 项目,因此我创建了到它的路由。我想要访问的第一个表是 my_database 调用 users 中的表。它具有属性user_id(主整数键)和created_on(带时区的时间戳)。

我已将我的 Vapor 项目链接到 my_database 以便我可以创建新模型。但是,如果我想访问预先存在的表users,该怎么办?以下是我根据文档和一些教程拼凑而成的内容:

我的初始模型:

final class Users: Model {

static let name = "users"

typealias ID = Int
typealias Database = PostgreSQLDatabase

static let idKey: WritableKeyPath<Users, Int?> = \.user_id

var user_id: Int?
var created_on: Date
}

extension Users: Content { }

我的迁移(我认为这只是一个“空白”迁移,只是为了将项目挂接到表上?):

struct FirstMigration: PostgreSQLMigration {
static func prepare(on conn: PostgreSQLConnection) -> EventLoopFuture<Void> {
    return conn.future()
}

static func revert(on conn: PostgreSQLConnection) -> EventLoopFuture<Void> {
    return Future<Void>.done(on: conn)
   }
}

我的配置:

var migrations = MigrationConfig()
migrations.add(migration: FirstMigration.self, database: .psql)
services.register(migrations)

非常感谢任何指导!

最佳答案

您不需要迁移。您需要使模型确认Migration 并将模型添加为迁移,或者设置静态defaultDatabase 属性。那么你应该可以走了。

PS - 我认为您需要 entity 而不是 name 来告诉它表名是什么。

关于swift - 将我的 Fluent 模型链接到预先存在的数据库表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60104516/

相关文章:

ios - 图像附件作为 NSAttributedstring 中的第一项(左对齐)

swift - 设置 GKARC4RandomSource 的种子

postgresql - 如何更有效地更新此表中的 13 亿行?

postgresql - 为什么 postgres set_config 的 is_local = true 不保留整个事务的变量?

swift UIButton.selected 不起作用

ios - navigationItem.setHidesBackButton 隐藏了箭头,但是 "Back"这个词仍然存在

sql - Postgres 基于 2 列聚合结果

fluent - 在 Fluent+Vapor 中查询子项

swift - 如何使用 vapor 3.x 构建 vapor 工具箱

swift - 构建 Vapor 3 框架时出现 Xcode 错误