gpt4 book ai didi

swift - Vapor 连接到 SQLite 数据库

转载 作者:可可西里 更新时间:2023-11-01 00:28:43 24 4
gpt4 key购买 nike

我正在尝试使用 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

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

像这样:

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

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com