Skip to content

Class

BooleanProperty

A Fluent model property which represents a boolean (true/false) value.
@propertyWrapper final class BooleanProperty<Model, Format> where Model : Fields, Format : BooleanPropertyFormat

Overview

By default, Bool properties are stored in a database using the storage format defined by the database driver, which corresponds to using the .bool data type on the appropriate field in a migration. This property wrapper allows specifying an alternative storage format - such the strings “true” and “false” - which is automatically translated to and from a Swift Bool when loading and saving the owning model. This is expected to be most useful when working with existing database schemas.

Example:

final class MyModel: Model {
    let schema = "my_models"

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

    // This field will be stored using the database's native boolean format.
    @Field(key: "rawEnabled") var rawEnabled: Bool

    // This field will be stored as a string, either "true" or "false".
    @Boolean(key: "enabled", format: .trueFalse) var enabled: Bool

    init() {}
}

struct MyModelMigration: AsyncMigration {
    func prepare(on database: Database) async throws -> Void {
        try await database.schema(MyModel.schema)
            .id()
            .field("rawEnabled", .bool, .required)
            .field("enabled", .string, .required)
            .create()
    }

    func revert(on database: Database) async throws -> Void { try await database.schema(MyModel.schema).delete() }
}

Topics

Initializers

Instance Properties

Default Implementations

Relationships

Conforms To