簡體   English   中英

Swift 5.2 Xcode 11.4 Vapor 4.0.0 我應該如何在我的 model 中編碼 PK?

[英]Swift 5.2 Xcode 11.4 Vapor 4.0.0 how should I code the PK in my model?

我的Package.swift文件如下所示:

.package(url: "https://github.com/vapor/vapor.git", from: "4.0.0-rc"),
.package(url: "https://github.com/vapor/fluent.git", from: "4.0.0-rc"),
.package(url: "https://github.com/vapor/fluent-postgres-driver.git", from: "2.0.0-rc")

我的config.swift文件如下所示:

app.databases.use(.postgres(
    hostname: Environment.get("DATABASE_HOST") ?? "localhost",
    username: Environment.get("DATABASE_USERNAME") ?? "postgres",
    password: Environment.get("DATABASE_PASSWORD") ?? "secret",
    database: Environment.get("DATABASE_NAME") ?? "mydb2"
), as: .psql)

我的 model 看起來像:

import Fluent
import Vapor


final class Complaint: Model, Content {

    static let schema = "cw_complaint5"

    @ID(key: .id)
    var id: UUID?

    @Field(key: "issue_description")
    var issue_description: String

    // etc.
    init() { }
}

在 Xcode 中,項目構建正常,此GET路由運行正常:

http://localhost:8080/complaint

但是當我運行POST路由時,響應正文中出現錯誤:

{
    "error": true,
    "reason": "Value of type 'UUID' required for key 'id'."
}

在 Vapor 3 中, POST路由對於插入新行(省略 JSON 請求正文中的 ID)和更新現有行都很好。 PostgreSQL 11.3 上的表描述如下:

mydb2=# \d+ cw_complaint5
                                              Table "public.cw_complaint5"
        Column        |          Type           | Collation | Nullable | Default | Storage  | Stats target | Description 
----------------------+-------------------------+-----------+----------+---------+----------+--------------+-------------
 id                   | integer                 |           | not null |         | plain    |              | 
 row                  | smallint                |           |          |         | plain    |              | 
 document_number      | integer                 |           | not null |         | plain    |              |
...etc...
county_id            | integer                 |           |          |         | plain    |              | 
 city_id              | integer                 |           |          |         | plain    |              | 
 operator_id          | integer                 |           |          |         | plain    |              | 
Indexes:
    "cw_complaint5_pkey" PRIMARY KEY, btree (id)
Check constraints:
    "cw_complaint5_row_check" CHECK ("row" >= 0)
Foreign-key constraints:
    "cw_complaint5_city_id_fkey" FOREIGN KEY (city_id) REFERENCES cw_city5(id)
    "cw_complaint5_county_id_fkey" FOREIGN KEY (county_id) REFERENCES cw_county5(id)
    "cw_complaint5_operator_id_fkey" FOREIGN KEY (operator_id) REFERENCES cw_operator5(id)

(END)

失敗的POST請求(更新現有行)的請求正文如下所示:

{"id":729,"issue_description":"test","document_number":99,"api_state_code":88,"api_county_code":11,"section":22,"city_id":51,"county_id":56,"operator_id":4415}

您的問題是Complaint模型的 ID 類型是UUID ,但是在您的POST請求正文中,您傳入了一個Int值。 由於您正在遷移已具有使用 integer ID 定義的數據庫的現有項目,因此最好的解決方案是更改模型的 ID 類型。

因為 Fluent 4 試圖支持所有數據庫,所以默認情況下它只支持 UUID ID 類型。 您可以有一個自定義 ID 類型,如下所示:

@ID(custom: "id", generatedBy: .database) var id: Int?

這將允許您的 model 使用您當前的數據庫表結構並在您的POST請求正文中獲取 integer ID。

您的 model 最終將如下所示:

final class Complaint: Model, Content {

    static let schema = "cw_complaint5"

    @ID(custom: "id", generatedBy: .database)
    var id: Int?

    @Field(key: "issue_description")
    var issue_description: String

    // etc.
    init() { }
}

解決方法:序列化PostgreSQL中的表:

mydb2=# ALTER TABLE cw_complaint5 DROP COLUMN id;

mydb2=# ALTER TABLE cw_complaint5 ADD COLUMN id SERIAL PRIMARY KEY;

然后插入一行(在 xcode 11.4 vapor 4 fluentpostgresql 中)從您的 POST 請求 json 中刪除 id 例如:

{"section":1,"operator_id":4415 ... etc.}

要更新現有行,請在 json 中包含 id。 routes.swift 中的以下內容同時處理插入和更新:

app.post("complaint") { req -> EventLoopFuture<Complaint> in
    let complaint = try req.content.decode(Complaint.self)
    if let id = complaint.id {
        print("60p \(id)") // Optional(6005)
    }
    return complaint.save(on: req.db)
        .map { complaint }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM