Lin*_*rth 2 sqlite swift 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)
Run Code Online (Sandbox Code Playgroud)
在数据库中,有一个名为的表posts,我想查询以下表并返回所有条目:
这是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 { }
Run Code Online (Sandbox Code Playgroud)
我还在以下位置添加了迁移configure.swift:
var migrations = MigrationConfig()
migrations.add(model: Post.self, database: .sqlite)
services.register(migrations)
Run Code Online (Sandbox Code Playgroud)
在中routes.swift,我将posts路线定义如下:
router.get("posts") { req in
return Post.query(on: req).all()
}
Run Code Online (Sandbox Code Playgroud)
现在,在致电时localhost:8080/posts,我得到:
[]
Run Code Online (Sandbox Code Playgroud)
我没有正确连接数据库吗?
我错过了什么吗?
fluent生成的表名似乎与您的数据库表名不同,因为Fluent生成的表名与Model类名相同。就你而言Post。
entity在模型类中添加静态属性Post以定义自定义表名称。
像这样:
public static var entity: String {
return "posts"
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
261 次 |
| 最近记录: |