我是蒸汽新手,我被困住了。我正在关注本教程:https ://www.xplusz.com/how-to-do-basic-crud/但我使用的是 MySQL 数据库而不是 postgresql 数据库。
所以这是我的代码:Patient.swift
import Foundation
import Vapor
import Fluent
final class Patient: Model {
var id: Node?
var firstName: String
var lastName: String
var exists: Bool = false
init(firstName: String, lastName: String) {
self.id = nil
self.firstName = firstName
self.lastName = lastName
}
init(node: Node, in context: Context) throws {
id = try node.extract("id")
firstName = try node.extract("first_name")
lastName = try node.extract("last_name")
}
func makeNode(context: Context) throws -> Node {
return try Node(node: [
"id": id,
"first_name": firstName,
"last_name": lastName
])
}
static func prepare(_ database: Database) throws {
try database.create("patients") { users in
users.id()
users.string("first_name")
users.string("last_name")
}
}
static func revert(_ database: Database) throws {
try database.delete("patients")
}
}
main.swift
import Vapor
import VaporMySQL
let drop = Droplet(
providers:[VaporMySQL.Provider.self]
)
drop.get { req in
return try drop.view.make("welcome", [
"message": drop.localization[req.lang, "welcome", "title"]
])
}
drop.get("version"){request in
if let db = drop.database?.driver as? MySQLDriver{
let version = try db.raw("SELECT version()")
return try JSON(node: version)
}else{
return "No db connection"
}
}
drop.post("patients") { request in
print(request.json)
var patient = try Patient(node: request.json)
try patient.save()
return patient
}
drop.get("patients"){request in
return try JSON(node: Patient.all().makeNode())
}
drop.resource("posts", PostController())
drop.run()
如果我运行版本,一切正常:
[
{
"version()": "5.7.14"
}
]
但例如,如果我运行 post 或 get requests,我会收到一个错误:
教程并没有首先讨论在数据库中创建表,但这就是准备函数的内容吧?还有什么问题?
mysql.json
{
"host": "localhost",
"user": "root",
"password": "",
"database": "development",
"port": "3306",
"encoding": "utf8"
}