【问题标题】:Vapor connect to SQLite Database蒸汽连接到 SQLite 数据库
【发布时间】:2019-01-21 15:09:07
【问题描述】:

我正在尝试使用 SQLite 设置 Vapor 3 项目。
configure.swift 文件中,我有以下与 sqlite 相关的设置:

try services.register(FluentSQLiteProvider())

...

// Get the root directory of the project
// I have verified that the file is present at this path
let path = DirectoryConfig.detect().workDir + "db_name.db"
let sqlite: SQLiteDatabase
do {
    sqlite = try SQLiteDatabase(storage: .file(path: path))
    print("connected") // called
} catch {
    print(error) // not called
    return
}

var databases = DatabasesConfig()
databases.add(database: sqlite, as: .sqlite)
services.register(databases)

在数据库中,我有一个名为posts 的表,我想从以下位置查询并返回所有条目:

这是 /Sources/App/Models/ 中的 Post 实现:

final class Post: Content {
    var id: Int?
    var title: String
    var body: String

    init(id: Int? = nil, title: String, body: String) {
        self.id = id
        self.title = title
        self.body = body
    }
}
extension Post: SQLiteModel, Migration, Parameter { }

我还在configure.swift中添加了迁移:

var migrations = MigrationConfig()
migrations.add(model: Post.self, database: .sqlite)
services.register(migrations)

routes.swift中,我定义posts路由如下:

router.get("posts") { req in
    return Post.query(on: req).all()
}

现在,当我拨打localhost:8080/posts 时,我得到:

[]

我没有正确连接数据库吗?
我错过了什么吗?

【问题讨论】:

    标签: swift sqlite vapor vapor-fluent


    【解决方案1】:

    似乎 fluent 生成的表名与您的 db 表名不同,因为 Fluent 生成的表名与 Model 类名相同。在你的情况下Post

    在模型类Post 中添加静态属性entity 以定义自定义表名。

    像这样:

    public static var entity: String {
        return "posts"
    }
    

    【讨论】:

      猜你喜欢
      • 2017-10-08
      • 2019-08-07
      • 2015-11-16
      • 1970-01-01
      • 2020-10-17
      • 2020-05-15
      • 2021-02-26
      • 2016-03-27
      • 1970-01-01
      相关资源
      最近更新 更多