Fluent Models

Models are the heart of Fluent. Unlike ORMs in other languages, Fluent doesn’t return untyped arrays or dictionaries for queries. Instead, you query the database using models. This allows the Swift compiler to catch many errors that have burdened ORM users for ages.

!!! info This guide provides an overview of the Model protocol and its associated methods and properties. If you are just getting started, check out the guide for your database at Fluent → Getting Started.

Model is a protocol in the Fluent module. It extends the AnyModel protocol which can be used for type-erasure.

Conformance

Both structs and classes can conform to Model, however you must pay special attention to Fluent’s return types if you use a struct. Since Fluent works asynchronously, any mutations to a value-type (struct) model must return a new copy of the model as a future result.

Normally, you will conform your model to one of the convenience models available in your database-specific package (i.e., PostgreSQLModel). However, if you want to customize additional properties, such as the model’s idKey, you will want to use the Model protocol itself.

Let’s take a look at what a basic Model conformance looks like.

  1. /// A simple user.
  2. final class User: Model {
  3. /// See `Model.Database`
  4. typealias Database = FooDatabase
  5. /// See `Model.ID`
  6. typealias ID = Int
  7. /// See `Model.idKey`
  8. static let idKey: IDKey = \.id
  9. /// The unique identifier for this user.
  10. var id: Int?
  11. /// The user's full name.
  12. var name: String
  13. /// The user's current age in years.
  14. var age: Int
  15. /// Creates a new user.
  16. init(id: Int? = nil, name: String, age: Int) {
  17. self.id = id
  18. self.name = name
  19. self.age = age
  20. }
  21. }

!!! tip Using final prevents your class from being sub-classed. This makes your life easier.

Associated Types

Model defines a few associated types that help Fluent create type-safe APIs for you to use. Take a look at AnyModel if you need a type-erased version with no associated types.

Database

This type indicates to Fluent which database you intend to use with this model. Using this information, Fluent can dynamically add appropriate methods and data types to any QueryBuilders you create with this model.

  1. final class User: Model {
  2. /// See `Model.Database`
  3. typealias Database = FooDatabase
  4. /// ...
  5. }

It is possible to make this associated type generic by adding a generic type to your class or struct (i.e, User<T>). This is useful for cases where you are attempting to create generic extensions to Fluent, like perhaps an additive service provider.

  1. final class User<D>: Model where D: Database {
  2. /// See `Model.Database`
  3. typealias Database = D
  4. /// ...
  5. }

You can add further conditions to D, such as QuerySupporting or SchemaSupporting. You can also dynamically extend and conform your generic model using extension User where D: ... { }.

That said, for most cases, you should stick to using a concrete type-alias wherever possible. Fluent 3 is designed to allow you to harness the power of your database by creating a strong connection between your models and the underlying driver.

ID

This property defines the type your model will use for its unique identifier.

  1. final class User: Model {
  2. /// See `Model.ID`
  3. typealias ID = UUID
  4. /// ...
  5. }

This will usually be something like Int, UUID, or String although you can theoretically use any type you like.

Properties

There are several overridable properties on Model that you can use to customize how Fluent interacts with your database.

Name

This String will be used as a unique identifier for your model whenever Fluent needs one.

  1. final class User: Model {
  2. /// See `Model.name`
  3. static let name = "user"
  4. /// ...
  5. }

By default, this is the type name of your model lowercased.

Entity

Entity is a generic word used to mean either “table” or “collection”, depending on which type of backend you are using for Fluent.

  1. final class Goose: Model {
  2. /// See `Model.entity`
  3. static let entity = "geese"
  4. /// ...
  5. }

By default, this property will be name pluralized. Overriding this property is useful in situations where language fails you and the plural form of a word is very irregular.

ID Key

The ID key is a writeable key path that points to your model’s unique identifier property.

Usually this will be a property named id (for some databases it is _id). However you can theoretically use any key you like.

  1. final class User: Model {
  2. /// See `Model.ID`
  3. typealias ID = String
  4. /// See `Model.entity`
  5. static let idKey = \.username
  6. /// The user's unique username
  7. var username: String?
  8. /// ...
  9. }

The idKey property must point to an optional, writeable (var) property with type matching ID.

Lifecycle

There are several lifecycle methods on Model that you can override to hook into Fluent events.

method description throwing
willCreate Called before Fluent saves your model (for the first time) Cancels the save.
didCreate Called after Fluent saves your model (for the first time) Save completes. Query fails.
willUpdate Called before Fluent saves your model (subsequent saves) Cancels the save.
didUpdate Called after Fluent saves your model (subsequent saves) Save completes. Query fails.
willRead Called before Fluent returns your model from a fetch query. Cancels the fetch.
willDelete Called before Fluent deletes your model. Cancels the delete.

Here’s an example of overriding the willUpdate(on:) method.

  1. final class User: Model {
  2. /// ...
  3. /// See `Model.willUpdate(on:)`
  4. func willUpdate(on connection: Database.Connection) throws -> Future<Self> {
  5. /// Throws an error if the username is invalid
  6. try validateUsername()
  7. /// Return the user. No async work is being done, so we must create a future manually.
  8. return Future.map(on: connection) { self }
  9. }
  10. }

CRUD

The model offers basic CRUD method (create, read, update, delete).

Create

This method creates a new row / item for an instance of your model in the database.

If your model does not have an ID, calls to .save(on:) will redirect to this method.

  1. let didCreate = user.create(on: req)
  2. print(didCreate) /// Future<User>

!!! info If you are using a value-type (struct), the instance of your model returned by .create(on:) will contain the model’s new ID.

Read

Two methods are important for reading your model from the database, find(_:on:) and query(on:).

  1. /// Finds a user with ID == 1
  2. let user = User.find(1, on: req)
  3. print(user) /// Future<User?>
  1. /// Finds all users with name == "Vapor"
  2. let users = User.query(on: req).filter(\.name == "Vapor").all()
  3. print(users) /// Future<[User]>

Update

This method updates the existing row / item associated with an instance of your model in the database.

If your model already has an ID, calls to .save(on:) will redirect to this method.

  1. /// Updates the user
  2. let didUpdate = user.update(on: req)
  3. print(didUpdate) /// Future<User>

Delete

This method deletes the existing row / item associated with an instance of your model from the database.

  1. /// Deletes the user
  2. let didDelete = user.delete(on: req)
  3. print(didDelete) /// Future<Void>

Methods

Model offers some convenience methods to make working with it easier.

Require ID

This method return’s the models ID or throws an error.

  1. let id = try user.requireID()