Skip to content

Instance Method

model(_:prefix:keyEncodingStrategy:nilEncodingStrategy:userInfo:)

Use an Encodable value to generate a row to insert and add that row to the query.
@discardableResult func model(_ model: some Encodable, prefix: String? = nil, keyEncodingStrategy: SQLQueryEncoder.KeyEncodingStrategy = .useDefaultKeys, nilEncodingStrategy: SQLQueryEncoder.NilEncodingStrategy = .default, userInfo: [CodingUserInfoKey : any Sendable] = [:]) throws -> Self

Parameters

model

A value to insert. This can be any encodable type which represents an aggregate value.

prefix

See prefix.

keyEncodingStrategy

See keyEncodingStrategy.

nilEncodingStrategy

See ``SQLQueryEncoder/nilEncodingStrategy-swift.property`.

userInfo

See userInfo.

Discussion

Example usage:

let earth = Planet(id: nil, name: "Earth", isInhabited: true)

try await sqlDatabase.insert(into: "planets")
    .model(earth, keyEncodingStrategy: .convertToSnakeCase)
    .run()

// Effectively the same as:
try await sqlDatabase.insert(into: "planets")
    .columns("id", "name", "is_inhabited")
    .values(SQLBind(earth.id), SQLBind(earth.name), SQLBind(earth.isInhabited))
    .run()

Note

The term “model” does not refer to Fluent’s Model type. Fluent models are not compatible with this method or any of its variants.