我正在尝试使用 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
时,我得到:
[]
我是否没有正确连接数据库?
我错过了什么吗?
最佳答案
Fluent 生成的表名称似乎与数据库表名称不同,因为 Fluent 生成的表名称与 Model
类名称相同。在您的情况下发布
。
在模型类 Post
中添加静态属性 entity
以定义自定义表名称。
像这样:
public static var entity: String {
return "posts"
}
关于swift - Vapor 连接到 SQLite 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54292759/