Skip to content

Protocol

ModelAlias

Describes a model whose schema has an alias.
@dynamicMemberLookup protocol ModelAlias : Schema

Overview

The ModelAlias protocol allows creating model types which are identical to an existing Model except that any Fluent query referencing the aliased type will use the provided alias name to refer to the model’s schema rather than the one specified by the model type. This allows, for example, referencing the same model more than once within the same query, such as when joining to a a parent model twice in the same query when the original model has multiple parent references of the same type.

Types conforming to this protocol can be used anywhere the original model’s type may be referenced. The alias type will mirror the space and schema of the original model, and provide its name for the alias property, affecting the result of the schemaOrAlias accessor. This accessor is used anywhere that a schema name that has been aliased may appear in place of the original.

Example:

final class Team: Model {
    static                   let schema = "teams"
    @ID(   key: .id)         var id: UUID?
    @Field(key: "name")      var name: String
    init() {}
}
final class Match: Model {
    static                       let schema = "matches"
    @ID(    key: .id)            var id: UUID?
    @Parent(key: "home_team_id") var homeTeam: Team
    @Parent(key: "away_team_id") var awayTeam: Team
    init() {}
}
final class HomeTeam: ModelAlias { static let name = "home_teams" ; let model = Team() }
final class AwayTeam: ModelAlias { static let name = "away_teams" ; let model = Team() }

for match in try await Match.query(on: self.database)
    .join(HomeTeam.self, on: \Match.$homeTeam.$id == \HomeTeam.$id)
    .join(AwayTeam.self, on: \Match.$awayTeam.$id == \AwayTeam.$id)
    .all()
{
    self.database.logger.debug("home: \(try match.joined(HomeTeam.self))")
    self.database.logger.debug("away: \(try match.joined(AwayTeam.self))")
}

Topics

Associated Types

  • Model
    The model type to be aliased.

Instance Properties

  • model
    An instance of the orignal model type. Holds returned data from lookups, and is used as a data source for CRUD operations.

Subscripts

Type Properties

  • name
    The actual alias name to be used in place of Model.schema.

Relationships

Inherits From

  • Fields
  • Schema
  • Swift.Decodable
  • Swift.Encodable
  • Swift.Sendable
  • Swift.SendableMetatype