Swift Academy · Lesson

Fluent ORM and Models

Persist data with Vapor's Fluent ORM.

Lesson 3 of 413 steps

Fluent ORM and Models is a free Swift Academy lesson on CoddyKit. This is lesson 3 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Swift Academy learning path, and your progress syncs across the web and the CoddyKit app. The Swift Academy course includes 4 lessons in total.

What Is Fluent?

Fluent is Vapor's ORM. It maps Swift classes to database rows, supporting PostgreSQL, MySQL, SQLite, and MongoDB through a single API. You write Swift; Fluent writes SQL.

import Fluent
import Vapor

Defining a Model

A Fluent model is a final class conforming to Model and usually Content. It declares a schema (table name) and an @ID property for the primary key.

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

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

    init() {}
}

The @Field Property Wrapper

Map a stored column with @Field. The key is the database column name. Add one property per column you want persisted.

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

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

A Complete Model

Models also need a memberwise initializer (in addition to the required empty init()) so you can create instances in code.

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
    }
}

Migrations

A migration creates or alters the database schema. It conforms to AsyncMigration and implements prepare (apply) and revert (undo).

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()
    }
}

Registering Migrations

Add migrations to app.migrations in your configuration, then run them with app.autoMigrate() or the migrate command.

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

Saving a Record

Create a model instance and call save(on:) with the request's database. Fluent issues an INSERT and fills in the generated 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
}

Querying Records

Use Model.query(on:) to build queries fluently. .all() returns every row; chain filters and sorts as needed.

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

Filtering and Finding by ID

find(_:on:) fetches by primary key, returning an optional. filter narrows results by column values.

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

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

Updating and Deleting

Mutate a fetched model's properties and call update(on:), or remove it with delete(on:). Both run asynchronously against the database.

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)
}

Relationships

Fluent models relationships with property wrappers: @Parent and @Child for one-to-one/one-to-many, and @Siblings for many-to-many. They define foreign keys and enable eager loading with .with(...).

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

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

Quick Check: Fluent

Test your ORM understanding.

Recap: Fluent ORM and Models

You can now persist data with Fluent:

  • Define a final class Model with @ID and @Field property wrappers and a schema.
  • Create tables via AsyncMigration and run them with autoMigrate().
  • CRUD with save, query(on:), find, update, and delete.
  • Model relationships with @Parent, @Child, and @Siblings, eager-loading via .with.
Free to start

Learn Swift with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
122
Lessons
409

Frequently Asked Questions

Is the “Fluent ORM and Models” lesson free?

Yes — any 3 lessons of the Swift Academy learning path, including “Fluent ORM and Models”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Swift Academy course includes 4 lessons in total.

What will I learn in “Fluent ORM and Models”?

Persist data with Vapor's Fluent ORM. You practise Swift Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Swift Academy?

No prior experience is required. Swift Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 3 of 4.

How long does the “Fluent ORM and Models” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Swift Academy lesson?

Yes. Every Swift Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Routing and Request Handling
  2. Content and JSON Encoding
  3. Fluent ORM and Models
  4. Middleware and Authentication
← Back to Swift Academy