Fluent提供了一種簡單、簡單愿题、安全的API损俭,用于處理持久數(shù)據(jù)。每個數(shù)據(jù)庫表/集合都由一個可用于與數(shù)據(jù)交互的Model
表示潘酗。Fluent支持常見的操作撩炊,如創(chuàng)建、讀取崎脉、更新和刪除模型拧咳。它還支持更高級的操作,比如連接囚灼、關(guān)聯(lián)和軟刪除骆膝。
筆記
不要忘記將import FluentProvider
(或您的其他數(shù)據(jù)庫提供程序)添加到您的Swift文件的頂部。
默認情況下灶体,F(xiàn)luent自帶SQLite阅签。您可以通過SQLite快速地使用它提供的內(nèi)存數(shù)據(jù)庫來搭建應(yīng)用程序。默認情況下蝎抽,這是默認啟用的政钟。要了解更多關(guān)于配置數(shù)據(jù)庫的信息,請查看可用的驅(qū)動程序(在本篇最后)樟结。
創(chuàng)建一個模型(Creating a Model)
模型是數(shù)據(jù)庫中Swift數(shù)據(jù)的展示养交。因此,它們對于大多數(shù)Fluent的api來說都是至關(guān)重要的瓢宦。
讓我們來看看一個簡單的模型是什么樣子的碎连。
final class Pet: Model {
var name: String
var age: Int
let storage = Storage()
init(row: Row) throws {
name = try row.get("name")
age = try row.get("age")
}
init(name: String, age: Int) {
self.name = name
self.age = age
}
func makeRow() throws -> Row {
var row = Row()
try row.set("name", name)
try row.set("age", age)
return row
}
}
在這里,我們創(chuàng)建了一個簡單的類寵物(Pet
)驮履,名字和年齡鱼辙。我們將添加一個簡單的init方法來創(chuàng)建新的寵物對象。
儲存(Storage)
storage
屬性允許Fluent在模型中存儲額外的信息——比如模型的數(shù)據(jù)庫id玫镐。
行(Row)
Row
結(jié)構(gòu)體表示一個數(shù)據(jù)庫行倒戏。您的模型應(yīng)該能夠?qū)?shù)據(jù)庫行進行解析和序列化。
解析(Parse)
下面是從數(shù)據(jù)庫中解析Pet的代碼恐似。
final class Pet: Model {
...
init(row: Row) throws {
name = try row.get("name")
age = try row.get("age")
}
}
序列化(Serialize)
下面是將Pet序列化到數(shù)據(jù)庫的代碼杜跷。
final class Pet: Model {
...
func makeRow() throws -> Row {
var row = Row()
try row.set("name", name)
try row.set("age", age)
return row
}
}
準備數(shù)據(jù)庫(Preparing the Database)
為了使用您的模型,您可能需要使用適當?shù)哪J絹頊蕚鋽?shù)據(jù)庫。
準備(Preparation)
你可以通過將你的模型繼承Preparation
來做到這一點葱椭。
extension Pet: Preparation {
static func prepare(_ database: Database) throws {
try database.create(self) { pets in
pets.id()
pets.string("name")
pets.int("age")
}
}
static func revert(_ database: Database) throws {
try database.delete(self)
}
}
在這里捂寿,我們創(chuàng)建了一個簡單的表,看起來如下:
id | name | age |
---|---|---|
<database id type> | string | int |
添加到Droplet(Add to Droplet)
現(xiàn)在孵运,您可以將模型添加到配置的準備中秦陋,以便在應(yīng)用程序啟動時準備好數(shù)據(jù)庫。
import Vapor
import FluentProvider
let config = try Config()
config.preparations.append(Pet.self)
let drop = try Droplet(config)
...
使用模型(Using Models)
現(xiàn)在我們已經(jīng)創(chuàng)建了模型并準備好了數(shù)據(jù)庫治笨,我們可以使用它來保存和從數(shù)據(jù)庫中獲取數(shù)據(jù)驳概。
保存(Save)
要保存一個模型,請調(diào)用.save()
旷赖。將自動創(chuàng)建模型的新標識符顺又。
let dog = Pet(name: "Spud", age: 5)
try dog.save()
print(dog.id) // the newly saved pet's id
查找(Find)
您可以使用它的ID從數(shù)據(jù)庫中獲取一個模型。
guard let dog = try Pet.find(42) else {
throw Abort.notFound
}
print(dog.name) // the name of the dog with id 42
過濾器(Filter)
您還可以使用過濾器搜索模型等孵。
let dogs = try Pet.makeQuery().filter("age", .greaterThan, 2).all()
print(dogs) // all dogs older than 2
驅(qū)動(Drivers)
查看數(shù)據(jù)庫(database)部分稚照,了解更多關(guān)于不同數(shù)據(jù)庫驅(qū)動程序的信息,您可以使用Fluent的數(shù)據(jù)庫驅(qū)動程序俯萌。