Vapor文檔學(xué)習(xí)二十:FLUENT - Model

Model協(xié)議是你應(yīng)用中任何model都贏準(zhǔn)守的基礎(chǔ)協(xié)議,尤其是持久化存儲(chǔ)的模型。

Model只能在Vapor中使用,在Fluent中是使用Entity。

Example

讓我們創(chuàng)建一個(gè)簡單的user模型:

final class User {
    var name: String

    init(name: String) {
        self.name = name
    }
}

要遵守Model協(xié)議,先要引入VaporFluent。

import Vapor
import Fluent

然后遵守協(xié)議:

final class User: Model {
    ...
}

然后編輯器會(huì)通知你必須實(shí)現(xiàn)某些方法。

ID

第一個(gè)必須實(shí)現(xiàn)的就是id屬性,數(shù)據(jù)庫獲取model都是通過id作為標(biāo)識(shí)符。如果idnil,那么在數(shù)據(jù)保存的時(shí)候會(huì)自定設(shè)置id。

final class User: Model {
    var id: Node?
    ...
}

Node Initializable

然后必須實(shí)現(xiàn)的就是將持久化存儲(chǔ)數(shù)據(jù)創(chuàng)建為model的方法。Model是遵守了NodeRepresentable協(xié)議。

final class User: Model {
    init(node: Node, in context: Context) throws {
        id = try node.extract("id")
        name = try node.extract("name")
    }
    ...
}

idname是數(shù)據(jù)庫中存儲(chǔ)的字段或者我們需要的列。使用try來調(diào)用extract是因?yàn)樵谧侄尾淮嬖诨蛘咦侄晤愋筒徽_的情況下會(huì)拋出異常。

Node Representable

現(xiàn)在已經(jīng)介紹了如何初始化模型,那我們來看看如何將模型保存到數(shù)據(jù)庫中。我們借助NodeRepresentable協(xié)議實(shí)現(xiàn)。

final class User: Model {
    func makeNode(context: Context) throws -> Node {
        return try Node(node: [
            "id": id,
            "name": name
        ])
    }
    ...
}

當(dāng)User被保存的時(shí)候就會(huì)調(diào)用makeNode方法,并且將Node保存到數(shù)據(jù)庫中。idname就是我們希望保存的列的名稱或者是在數(shù)據(jù)庫中的字段名。

通常情況下,你不需要關(guān)心makeNode(context :)方法的context參數(shù)。 它是協(xié)議的一部分,允許在更高級或特定場景中進(jìn)行擴(kuò)展。

Preparations

一些數(shù)據(jù)庫,像MySQL,需要對新的模式做準(zhǔn)備。在MySQL中這意味著需要?jiǎng)?chuàng)建新的表。Preparations相當(dāng)于遷移,因?yàn)樗试S修改已經(jīng)創(chuàng)建的模式。

Prepare

假設(shè)我們正在使用SQL數(shù)據(jù)庫。 要為我們的User類準(zhǔn)備數(shù)據(jù)庫,我們需要?jiǎng)?chuàng)建一個(gè)表。 如果您使用的是像Mongo這樣的數(shù)據(jù)庫,您可以不識(shí)閑此方法。

final class User {
    static func prepare(_ database: Database) throws {
        try database.create("users") { users in
            users.id()
            users.string("name")
        }
    }
    ...
}

我們創(chuàng)建了一個(gè)users表,具有idname兩個(gè)字段,這與init(node: Node)makeNode() -> Node方法相匹配。

Revert

當(dāng)調(diào)用vapor run prepare --revert指令時(shí),就會(huì)創(chuàng)建一個(gè)可選的可還原的preparation。

final class User {
    static func revert(_ database: Database) throws {
        try database.delete("users")
    }
    ...
}

這樣就刪除了users

Preparations as Migrations

在情景初始化之后,如果你想向表中插入一個(gè)字段,你只需要?jiǎng)?chuàng)建一個(gè)遵守Preparation協(xié)議的類或結(jié)構(gòu)體:

struct AddFooToBar: Preparation {
    static func prepare(_ database: Database) throws {
        try database.modify("bars", closure: { bar in
            bar.string("foo", length: 150, optional: false, unique: false, default: nil)
        })
    }

    static func revert(_ database: Database) throws {

    }
}

設(shè)置Droplet的時(shí)候添加一行代碼:drop.preparations.append(AddFooToBar.self)

Droplet

為了啟動(dòng)應(yīng)用的時(shí)候運(yùn)行這些preparations, 你必須將Model添加到Droplet中。

let drop = Droplet()

drop.preparations.append(User.self)

Note:Preparations必須在drop.run()之前添加。

Full Model

看一下我們最終完成的User模型:

import Vapor
import Fluent

final class User: Model {
    var id: Node?
    var name: String

    init(name: String) {
        self.name = name
    }

    init(node: Node, in context: Context) throws {
        id = try node.extract("id")
        name = try node.extract("name")
    }

    func makeNode(context: Context) throws -> Node {
        return try Node(node: [
            "id": id,
            "name": name
        ])
    }

    static func prepare(_ database: Database) throws {
        try database.create("users") { users in
            users.id()
            users.string("name")
        }
    }

    static func revert(_ database: Database) throws {
        try database.delete("users")
    }
}

Interacting

現(xiàn)在User遵守了Model協(xié)議,然后添加了許多新的方法,比如find(),query(),makeJSON()等等。

Fetch

通過數(shù)據(jù)庫id查詢Model:

let user = try User.find(42)
Save

新創(chuàng)建的數(shù)據(jù)模型可以保存到數(shù)據(jù)庫:

var user = User(name: "Vapor")
try user.save()
print(user.id) // prints the new id
Delete

持久存儲(chǔ)的模型可以被刪除:

try user.delete()

Model vs. Entity

Model遵守了幾個(gè)額外的協(xié)議,而一個(gè)純粹的Entity沒有。

public protocol Model: Entity, JSONRepresentable, StringInitializable, ResponseRepresentable {}

通過以上協(xié)議,Model可以自動(dòng)轉(zhuǎn)化為JSON,Response對象,并且可以用在類型安全的路由上。

Options

改變 table/collection 名稱:

static var entity = "new_name"

</br>
<b>總結(jié):</b>本章通過User模型介紹了數(shù)據(jù)模型Model的創(chuàng)建與使用,并介紹了數(shù)據(jù)備份的方法。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容