Skip to content

Class

CompositeOptionalChildProperty

Declares an optional one-to-one relation between the referenced (“child”) model and the referencing (“parent”) model, where the parent model specifies its ID with CompositeIDProperty.
@propertyWrapper final class CompositeOptionalChildProperty<From, To> where From : Model, To : Model, From.IDValue : Fields

Overview

CompositeOptionalChildProperty serves the same purpose for child models with parents which use @CompositeID that OptionalChildProperty serves for parent models which use @ID.

Unfortunately, while the type of ID used by the child model makes no difference, limitations of Swift’s generics syntax make it impractical to support both @ID-using and @CompositeID-using models as the parent model with a single property type.

CompositeOptionalChildProperty cannot reference a ParentProperty or OptionalParentProperty; use OptionalChildProperty instead.

Example:

Note

This example is somewhat contrived; in reality, this kind of metadata would have much more complex relationships.

final class TableMetadata: Model {
    static let schema = "table_metadata"

    final class IDValue: Fields, Hashable {
        @Field(key: "table_schema") var schema: String
        @Field(key: "table_name")   var name: String
        init() {}
        static func ==(lhs: IDValue, rhs: IDValue) -> Bool { lhs.schema == rhs.schema && lhs.name == rhs.name }
        func hash(into hasher: inout Hasher) { hasher.combine(self.schema); hasher.combine(self.name) }
    }

    @CompositeID var id: IDValue?
    @CompositeParent(prefix: "meta") var metaTable: TableMetadata
    @CompositeOptionalChild(for: \.$metaTable) var realizedTable: TableMetadata?
    // ...

    struct CreateTableMigration: AsyncMigration {
        func prepare(on database: Database) async throws {
            try await database.schema(TableMetadata.schema)
                .field("table_schema", .string, .required)
                .field("table_name", .string, .required)
                .compositeIdentifier(over: ["table_schema", "table_name"])
                .field("meta_table_schema", .string, .required)
                .field("meta_table_name", .string, .required)
                .foreignKey(["meta_table_schema", "meta_table_name"], references: TableMetadata.schema, ["table_schema", "table_name"])
                // ...
                .create()
        }
    }
}

Topics

Initializers

Instance Properties

Instance Methods

Type Aliases

Default Implementations

Relationships

Conforms To