0Pricing
Swift Academy · 课时

Fluent ORM 与模型

使用 Vapor 的 Fluent ORM 持久化数据。

Fluent ORM 与模型 是 CoddyKit 上的免费 Swift Academy 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Swift Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Swift Academy 课程共包含 4 节课。

什么是 Fluent

Fluent 是 Vapor 的 ORM。它可以将 Swift 类映射到数据库行,并通过单一 API 支持 PostgreSQL、MySQL、SQLite 和 MongoDB。您编写 Swift,Fluent 编写 SQL。

import Fluent
import Vapor

定义模型

Fluent 模型是一个遵循 Model 且通常也遵循 Content 的 final class。它声明一个 schema(表名)和一个用于主键的 @ID 属性。

final class Planet: Model, Content {
    static let schema = "planets"

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

    init() {}
}

@Field 属性包装器

使用 @Field 映射存储列。键就是数据库列名。要持久化哪个列,就为其添加一个属性。

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

@Field(key: "diameter_km")
var diameterKm: Int

完整模型

模型还需要成员式初始化器(除了必需的空 init() 之外),这样您就可以在代码中创建实例。

final class Planet: Model, Content {
    static let schema = "planets"
    @ID(key: .id) var id: UUID?
    @Field(key: "name") var name: String
    init() {}
    init(id: UUID? = nil, name: String) {
        self.id = id
        self.name = name
    }
}

数据库迁移

数据库迁移用于创建或修改数据库结构。它遵循 AsyncMigration,并实现 prepare(应用)和 revert(撤销)。

struct CreatePlanet: AsyncMigration {
    func prepare(on db: Database) async throws {
        try await db.schema("planets")
            .id()
            .field("name", .string, .required)
            .create()
    }
    func revert(on db: Database) async throws {
        try await db.schema("planets").delete()
    }
}

注册数据库迁移

在配置中将数据库迁移添加到 app.migrations,然后使用 app.autoMigrate() 或 migrate 命令运行它们。

app.migrations.add(CreatePlanet())
try await app.autoMigrate()

保存记录

创建模型实例,并使用请求的数据库调用 save(on:)。Fluent 会执行 INSERT 并填充生成的 id。

app.post("planets") { req async throws -> Planet in
    let planet = try req.content.decode(Planet.self)
    try await planet.save(on: req.db)
    return planet
}

查询记录

使用 Model.query(on:) 以流畅方式构建查询。.all() 会返回所有行;您可以根据需要串联筛选和排序。

app.get("planets") { req async throws -> [Planet] in
    try await Planet.query(on: req.db).all()
}

按 ID 筛选和查找

find(_:on:) 会按主键获取记录,并返回一个可选值。filter 会根据列值缩小结果范围。

let earth = try await Planet.query(on: req.db)
    .filter(\.$name == "Earth")
    .first()

let byId = try await Planet.find(someUUID, on: req.db)

更新和删除

修改已获取模型的属性并调用 update(on:),或者使用 delete(on:) 将其删除。这两种操作都会异步针对数据库执行。

if let planet = try await Planet.find(id, on: req.db) {
    planet.name = "Renamed"
    try await planet.update(on: req.db)
    // or: try await planet.delete(on: req.db)
}

关系

Fluent 使用属性包装器为模型定义关系:@Parent 和 @Child 用于一对一/一对多关系,@Siblings 用于多对多关系。它们定义外键,并通过 .with(...) 支持预加载。

@Parent(key: "star_id")
var star: Star

// query eagerly loading the parent
Planet.query(on: req.db).with(\.$star).all()

快速检查:Fluent

请测试您对 ORM 的理解。

回顾:Fluent ORM 与模型

现在您可以使用 Fluent 持久化数据:

  • 定义包含 @ID 和 @Field 属性包装器以及 schema 的 final class Model。
  • 通过 AsyncMigration 创建表,并使用 autoMigrate() 运行迁移。
  • 使用 save、query(on:)、find、update 和 delete 执行增删改查。
  • 使用 @Parent、@Child 和 @Siblings 定义模型关系,并通过 .with 进行预加载。

常见问题解答

「Fluent ORM 与模型」课时是免费的吗?

是的 — 「Fluent ORM 与模型」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Swift Academy 课程的其余内容,请升级到 CoddyKit PRO。 Swift Academy 课程共包含 4 节课。

「Fluent ORM 与模型」这节课中我会学到什么?

使用 Vapor 的 Fluent ORM 持久化数据。 你通过在浏览器中直接运行的动手代码来练习 Swift Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Swift Academy 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Swift Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。

「Fluent ORM 与模型」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Swift Academy 课中编写并运行代码吗?

能。每节 Swift Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 路由与请求处理
  2. 内容与 JSON 编码
  3. Fluent ORM 与模型
  4. 中间件与身份验证
← 返回 Swift Academy