// 这是我在 youtube 上的 Paul Hudson 的教程中提出的问题的延续 -
我试图将项目添加到数据库(见下图) -
当我应该点击上图中的“添加”按钮时,这些框应该变成空的(见下图)。虽然 .Quantum Pizza 不会被添加到 .Statin Island Pizza 和 .Country Pizza 的列表中,因为我没有做进一步的编码),但应该如下图 -
但是,结果如下 -
现在,我发布代码 -----
配置.swift -
import Fluent
import FluentSQLite
import Vapor
import Leaf // added
public func configure(_ config: inout Config, _ env: inout Environment, _ services: inout Services) throws {
// Register routes to the router
let router = EngineRouter.default()
try routes(router)
services.register(router, as: Router.self)
let leafProvider = LeafProvider() // added
try services.register(leafProvider) // added
config.prefer(LeafRenderer.self, for: ViewRenderer.self)// added
let directoryConfig = DirectoryConfig.detect()
services.register(directoryConfig)
try services.register(FluentSQLiteProvider())
var databaseConfig = DatabasesConfig()
let db = try SQLiteDatabase(storage: .file(path:"\(directoryConfig.workDir)pizza.db"))
databaseConfig.add(database: db, as: .sqlite)
services.register(databaseConfig)
var migrationConfig = MigrationConfig()
migrationConfig.add(model: Pizza.self, database: .sqlite)
services.register(migrationConfig)
let serverConfigure = NIOServerConfig.default(hostname: "0.0.0.0", port: 9090)
services.register(serverConfigure)
}
路线.swift -
import Routing
import Vapor
import FluentSQLite
public func routes(_ router: Router) throws {
router.get { req -> Future <View> in
let Newyorker = Pizza(id: 5, name: "Statin Island Pizza", description: "Impractical Jokers Funny Pizza", price: 55)
let Traditional = Pizza(id: 5, name: "Country Pizza ", description: "Johny Cash Special", price: 55)
return try req.view().render("welcome",["pizza":[Newyorker,Traditional]])
}
router.post(Pizza.self, at: "add") { req, pizza -> Future<Response> in
return pizza.save(on:req).map(to:Response.self) { Pizza in
return req.redirect(to: "/")
}
}
}
Pizza.swift -
import Foundation
import Vapor
import FluentSQLite
struct Pizza: Encodable, Content, Decodable, SQLiteModel, Migration {
var id: Int?
var name: String
var description: String
var price: Int
}
叶屏幕截图(我尝试以正确的格式粘贴代码,但无法粘贴。因此添加了 screeshot)-
编辑 1:单击添加按钮后的屏幕截图 -
如果您需要,我很乐意为您提供任何进一步的信息。另外,我想知道我的问题的标题是否应该修改或应该添加任何内容。谢谢你。