swift - Vapor 连接到 SQLite 数据库

标签 swift sqlite vapor vapor-fluent

我正在尝试使用 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 的表,我想查询并返回其中的所有条目:

database table

这是 /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时,我得到:

[]

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

最佳答案

Fluent 生成的表名称似乎与数据库表名称不同,因为 Fluent 生成的表名称与 Model 类名称相同。在您的情况下发布

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

像这样:

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

关于swift - Vapor 连接到 SQLite 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54292759/

相关文章:

ios - 如何在XMPP中接受好友请求?

swift - 如何使用 NSNotification 将 sqlite.swift 的 Row 传递到另一个 Controller

php - PDO SQLite创建数据库默认权限

sqlite - Android SQLite 中的增量

swift - Vapor Swift 如何删除从 fileIO 收集的文件

linux - 是否可以在 Swift 中(在 Linux 下)使用 GNU 科学图书馆?

ios - 一个 iphone 应用程序是否可以读取另一个应用程序的日志?

android - 无法启动 Activity ComponentInfo

swift - Vapor Hello 样本中的强引用

swift - Vapor 4 : Children relation not eager loaded, 使用 $ 前缀访问