Model<TModel extends Model<TModel>> class abstract

Base class for Ormed models.

Ormed distinguishes between:

  • User-defined models (class User extends Model<User>) which are typically immutable value objects.
  • Generated tracked models ($User) which Ormed hydrates from queries and uses for change tracking, relation caching, and persistence helpers.

Many APIs in the model layer only behave correctly on tracked instances. Prefer using repositories (DataSource.repo<T>()) or queries (DataSource.query<T>()) to obtain tracked models.

User-defined model classes are usually immutable value objects:

@OrmModel(table: 'users')
class User extends Model<User> {
  const User({this.id, required this.email});
  final int? id;
  final String email;
}

Before using model helpers that hit the database, a connection must be configured.

In most apps, calling DataSource.init() is sufficient because it registers a default data source on ConnectionManager. For custom wiring, call Model.bindConnectionResolver(...).

Many instance helpers (such as save(), delete(), and relation loaders) require a tracked instance with an attached connection context.

Implemented types
Mixed-in types
Implementers
Available extensions

Constructors

Model()
const

Properties

attributes Map<String, Object?>

Available on Model<T>, provided by the ModelAttributeExtensions extension

Returns the raw tracked attributes map.
no setter
connection DriverAdapter?
The driver/connection associated with this model, if any.
no setterinherited
connectionResolver ConnectionResolver?
The resolver attached to this model, when present.
no setterinherited
createdAt CarbonInterface?

Available on Model<T>, provided by the ModelTimestampExtensions extension

Get the creation timestamp as a Carbon instance.
getter/setter pair
definition ModelDefinition<TModel>?
Typed accessor to the attached ModelDefinition, when available. Returns null for untracked models (they don't have attached definitions).
no setter
deletedAt CarbonInterface?

Available on Model<T>, provided by the ModelSoftDeleteExtensions extension

Get the soft delete timestamp as a Carbon instance.
getter/setter pair
exists bool
Whether this model has been persisted (loaded or saved).
no setter
hasConnection bool
Whether a resolver/connection has been attached.
no setterinherited
hasDefinition bool
Whether a ModelDefinition has been attached to this instance. Always false for untracked models.
no setter
hashCode int
The hash code for this object.
no setterinherited
loadedRelationNames Set<String>
Returns names of all loaded relations.
no setterinherited
loadedRelationNames Set<String>

Available on Model<T>, provided by the ModelAttributeExtensions extension

Returns names of all loaded relations.
no setter
loadedRelations Map<String, dynamic>
Returns a snapshot of all currently loaded relations.
no setterinherited
loadedRelations Map<String, dynamic>

Available on Model<T>, provided by the ModelAttributeExtensions extension

Returns all loaded relations as a map (property alias).
no setter
relations Map<String, dynamic>
Shorthand alias for loadedRelations.
no setterinherited
relations Map<String, dynamic>

Available on Model<T>, provided by the ModelAttributeExtensions extension

Returns all loaded relations as a map (shorthand for getLoadedRelations).
no setter
runtimeType Type
A representation of the runtime type of the object.
no setterinherited
timestamps bool
Whether automatic timestamps are enabled for this model instance.
no setter
touches TouchesList
Relation names that should be touched when this model is saved.
no setter
trashed bool

Available on Model<T>, provided by the ModelSoftDeleteExtensions extension

Check if the model has been soft deleted.
no setter
updatedAt CarbonInterface?

Available on Model<T>, provided by the ModelTimestampExtensions extension

Get the last update timestamp as a Carbon instance.
getter/setter pair
usesTimestamps bool
Whether this model uses timestamps after applying ignore scopes.
no setter

Methods

asMap({ValueCodecRegistry? registry}) Map<String, Object?>
Alias for toRecord for ergonomics when bridging to JSON/Maps.
associate(String relationName, Model<Model> parent) Future<TModel>
Associates a belongsTo parent model and updates the foreign key.
attach(String relationName, List ids, {Map<String, dynamic>? pivotData}) Future<TModel>
Attaches related models in a manyToMany relationship.
attachConnection(DriverAdapter driver) → void
Legacy helper for manually attaching a driver outside a resolver.
inherited
attachConnectionResolver(ConnectionResolver resolver) → void
Assigns the resolver responsible for this model instance.
inherited
attachModelDefinition(ModelDefinition<T> definition) → void

Available on Model<T>, provided by the ModelAttributeExtensions extension

Attaches a model definition to this model instance.
clearQueuedJsonMutations() → void
Clears any queued JSON mutations without persisting them.
clearRelations() → void

Available on Model<T>, provided by the ModelAttributeExtensions extension

Clears all loaded relations.
clearRelations() → void
Clears all cached relations.
inherited
createManyQuietlyRelation<TRelated extends Model<TRelated>>(String relationName, List<Object> attributesList) Future<List<TRelated>>
Creates multiple related models without firing model events.
createManyRelation<TRelated extends Model<TRelated>>(String relationName, List<Object> attributesList) Future<List<TRelated>>
Creates multiple related models through a hasMany relationship.
createQuietlyRelation<TRelated extends Model<TRelated>>(String relationName, Object attributes) Future<TRelated>
Creates a related model without firing model events.
createRelation<TRelated extends Model<TRelated>>(String relationName, Object attributes) Future<TRelated>
Creates a related model through a hasOne or hasMany relationship.
delete({bool force = false}) Future<void>
Deletes the record. Soft-deletes when supported unless force is true.
describeMutation(MutationPlan plan) StatementPreview
Returns the statement preview for a write plan.
inherited
describeQuery(QueryPlan plan) StatementPreview
Returns the statement preview for a read plan.
inherited
detach(String relationName, [List? ids]) Future<TModel>
Detaches related models in a manyToMany relationship.
dissociate(String relationName) Future<TModel>
Dissociates a belongsTo parent model and clears the foreign key.
expectDefinition() ModelDefinition<TModel>
Ensures the definition metadata is available, throwing when missing.
fill(Object attributes, {bool strict = false, ValueCodecRegistry? registry}) Model<TModel>
Mass assigns attributes, honoring fillable/guarded metadata.
fillAttributes(Map<String, Object?> payload, {bool strict = true, ValueCodecRegistry? registry}) Map<String, Object?>

Available on Model<T>, provided by the ModelAttributeExtensions extension

Fills attributes from payload, respecting fillable/guarded metadata.
fillIfAbsent(Object attributes, {bool strict = false, ValueCodecRegistry? registry}) Model<TModel>
Mass assigns only values that are currently absent.
forceDelete() Future<void>
Hard-deletes the record, bypassing soft-delete flows entirely.
forceFill(Object attributes, {ValueCodecRegistry? registry}) Model<TModel>
Temporarily disables mass-assignment protection while callback runs.
fresh({bool withTrashed = false, Iterable<String>? withRelations}) Future<TModel>
Returns a fresh instance of this model from the database.
getAttribute<TValue>(String key) → TValue?

Available on Model<T>, provided by the ModelAttributeExtensions extension

Returns an attribute value from the attribute store.
getAttributes() Map<String, Object?>

Available on Model<T>, provided by the ModelAttributeExtensions extension

Returns all tracked attributes as a map.
getChanges() Map<String, Object?>

Available on Model<T>, provided by the ModelAttributeExtensions extension

Returns all changed attributes with their new values (alias for getDirty).
getDirty() Map<String, Object?>

Available on Model<T>, provided by the ModelAttributeExtensions extension

Returns all changed attributes as a map.
getLoadedRelations() Map<String, dynamic>

Available on Model<T>, provided by the ModelAttributeExtensions extension

Returns all loaded relations as a map.
getOriginal([String? key]) Object?

Available on Model<T>, provided by the ModelAttributeExtensions extension

Returns the original (unmodified) value of an attribute.
getRelation<T>(String name) → T?
Retrieves a cached relation value typed as T.
inherited
getRelation<TRelation>(String relation) → TRelation?

Available on Model<T>, provided by the ModelAttributeExtensions extension

Returns a loaded relation value.
getRelationList<T>(String name) List<T>
Retrieves a list relation typed as T.
inherited
getRelationList<TRelation>(String relation) List<TRelation>

Available on Model<T>, provided by the ModelAttributeExtensions extension

Returns a loaded relation list.
hasAttribute(String key) bool

Available on Model<T>, provided by the ModelAttributeExtensions extension

Returns true if an attribute exists in the attribute store.
isDifferentFrom(Model<Model>? other) bool
Determine if two models are different.
isDirty([String? key]) bool

Available on Model<T>, provided by the ModelAttributeExtensions extension

Returns true if this model has been modified since it was loaded.
isSameAs(Model<Model>? other) bool
Determine if two models represent the same database record.
jsonPatch(String column, Map<String, Object?> delta) → void
Queues a JSON patch merge for column using the provided delta map.
jsonSet(String selector, Object? value) → void
Queues a JSON update using Laravel-style selector syntax (column->path). Call save to persist the change.
jsonSetPath(String column, String path, Object? value) → void
Queues a JSON update by explicitly providing path relative to column.
load(String relation, [PredicateCallback<OrmEntity>? constraint]) Future<TModel>
Lazily loads a relation on this model instance.
loadAvg(String relation, String column, {String? alias, PredicateCallback<OrmEntity>? constraint}) Future<TModel>
Lazily loads the average of a column in a relation.
loadCount(String relation, {String? alias, PredicateCallback<OrmEntity>? constraint}) Future<TModel>
Lazily loads the count of a relation.
loadExists(String relation, {String? alias, PredicateCallback<OrmEntity>? constraint}) Future<TModel>
Lazily loads the existence of a relation.
loadMany(Map<String, PredicateCallback<OrmEntity>?> relations) Future<TModel>
Lazily loads multiple relations with optional constraints.
loadMax(String relation, String column, {String? alias, PredicateCallback<OrmEntity>? constraint}) Future<TModel>
Lazily loads the maximum value of a column in a relation.
loadMin(String relation, String column, {String? alias, PredicateCallback<OrmEntity>? constraint}) Future<TModel>
Lazily loads the minimum value of a column in a relation.
loadMissing(Iterable<String> relations) Future<TModel>
Lazily loads multiple relations that haven't been loaded yet.
loadSum(String relation, String column, {String? alias, PredicateCallback<OrmEntity>? constraint}) Future<TModel>
Lazily loads the sum of a column in a relation.
markAsExisting() → void
Marks this model as existing in the database.
noSuchMethod(Invocation invocation) → dynamic
Invoked when a nonexistent method or property is accessed.
inherited
refresh({bool withTrashed = false, Iterable<String>? withRelations}) Future<TModel>
Reloads the latest row from the database, optionally including trashed.
relationLoaded(String relation) bool

Available on Model<T>, provided by the ModelAttributeExtensions extension

Returns true if a relation has been loaded in this instance.
relationLoaded(String name) bool
Checks if a relation has been loaded.
inherited
replaceAttributes(Map<String, Object?> attributes) → void

Available on Model<T>, provided by the ModelAttributeExtensions extension

Replaces all attributes with new values.
replicate({List<String>? except}) → TModel
Clone the model into a new, non-existing instance.
restore() Future<void>
Restores a soft-deleted record.
runMutation(MutationPlan plan) Future<MutationResult>
Runs a write plan through the attached resolver.
inherited
runSelect(QueryPlan plan) Future<List<Map<String, Object?>>>
Runs a read plan through the attached resolver.
inherited
save() Future<void>

Available on Model<T>, provided by the ModelTimestampExtensions extension

Saves the current model instance to the database.
save({bool returning = true, bool touch = true}) Future<TModel>
Persists the model using the active resolver and returns the stored copy.
saveManyRelation<TRelated extends Model<TRelated>>(String relationName, List<TRelated> related) Future<List<TRelated>>
Saves multiple related models through a hasMany relationship.
saveRelation<TRelated extends Model<TRelated>>(String relationName, TRelated related) Future<TRelated>
Saves a related model through a hasOne or hasMany relationship.
setAttribute(String key, Object? value) → void

Available on Model<T>, provided by the ModelAttributeExtensions extension

Sets an attribute value in the attribute store.
setAttributes(Map<String, Object?> attributes) → void

Available on Model<T>, provided by the ModelAttributeExtensions extension

Sets multiple attributes at once.
setRelation(String name, dynamic value) → void
Sets a relation value and marks it as loaded.
inherited
setRelation(String relation, dynamic value) → void

Available on Model<T>, provided by the ModelAttributeExtensions extension

Sets a relation value and marks it as loaded.
setRelations(Map<String, dynamic> relations) → void

Available on Model<T>, provided by the ModelAttributeExtensions extension

Sets multiple relations at once.
setRelations(Map<String, dynamic> relations) → void
Bulk sets multiple relations at once.
inherited
sync(String relationName, List ids, {Map<String, dynamic>? pivotData}) Future<TModel>
Syncs a manyToMany relationship to match the given IDs exactly.
syncOriginal() → void

Available on Model<T>, provided by the ModelAttributeExtensions extension

Syncs the original state to match current attributes.
syncRelationsFromQueryRow(Map<String, dynamic> rowRelations) → void
Syncs relations from a QueryRow into this model's cache.
inherited
syncRelationsFromQueryRow(Map<String, dynamic> row) → void

Available on Model<T>, provided by the ModelAttributeExtensions extension

Syncs relations from a query row map.
syncWithoutDetaching(String relationName, List ids, {Map<String, dynamic>? pivotData}) Future<TModel>
Syncs a manyToMany relationship without detaching existing records.
syncWithPivotValues(String relationName, List ids, Map<String, dynamic> pivotData) Future<TModel>
Syncs a manyToMany relationship with the same pivot data for all records.
toArray({ValueCodecRegistry? registry, bool includeHidden = false}) Map<String, Object?>
Converts the model into a metadata-aware map, honoring hidden/visible lists.
toggle(String relationName, List ids, {Map<String, dynamic>? pivotData}) Future<TModel>
Toggles the attachment of related models in a manyToMany relationship.
toJson({ValueCodecRegistry? registry, bool includeHidden = false}) String
Converts the model instance into JSON, applying the attribute metadata.
toRecord({ValueCodecRegistry? registry}) Map<String, Object?>
Serializes the model into a column map via its codec/definition.
toString() String
A string representation of this object.
inherited
touch([String? attribute]) Future<bool>
Touches the model's timestamp column and persists the change.
touch() Future<bool>

Available on Model<T>, provided by the ModelTimestampExtensions extension

Updates the updatedAt timestamp and persists it.
touchOwners() Future<void>
Touches the owning relations of the model.
unsetRelation(String name) → void
Removes a relation from the cache and marks it as not loaded.
inherited
unsetRelation(String relation) → void

Available on Model<T>, provided by the ModelAttributeExtensions extension

Unloads a relation.
updateExistingPivot(String relationName, dynamic id, Map<String, dynamic> pivotData) Future<TModel>
Updates pivot table attributes for an existing pivot record.
wasChanged(String key) bool

Available on Model<T>, provided by the ModelAttributeExtensions extension

Returns true if a specific attribute has been modified.
withoutTimestamps<T>(T callback()) → T
Disable timestamps for this model's runtime type during the callback scope.
withoutTouching<T>(T callback()) → T
Disable touching for this model's runtime type during the callback scope.

Operators

operator ==(Object other) bool
The equality operator.
inherited

Static Methods

all<TModel extends OrmEntity>({String? connection}) Future<List<TModel>>
Convenience to fetch every model instance.
anyExist<TModel extends OrmEntity>({String? connection}) Future<bool>
Check if any models exist in the database.
bindConnectionResolver({ConnectionResolverFactory? resolveConnection, ConnectionManager? connectionManager, String defaultConnection = 'default', ConnectionRole defaultRole = ConnectionRole.primary}) → void
Binds a global resolver factory so model helpers know how to persist.
count<TModel extends OrmEntity>({String? connection}) Future<int>
Count the number of models.
create<TModel extends Model<TModel>>(Map<String, dynamic> attributes, {String? connection}) Future<TModel>
Creates and immediately persists a new model from attributes map.
createOrFirst<TModel extends Model<TModel>>(Map<String, dynamic> attributes, {Map<String, dynamic> values = const {}, String? connection}) Future<TModel>
Create a new model or get the first existing one.
destroy<TModel extends Model<TModel>>(List<Object> ids, {String? connection}) Future<int>
Delete all models matching a condition (dangerous!).
factory<TModel extends Model<TModel>>({GeneratorProvider? generatorProvider}) ModelFactoryBuilder<TModel>
Returns a factory builder that mirrors Laravel’s Model::factory() DSL.
find<TModel extends OrmEntity>(Object id, {String? connection}) Future<TModel?>
Find a model by its primary key, returns null if not found.
findMany<TModel extends OrmEntity>(List<Object> ids, {String? connection}) Future<List<TModel>>
Find multiple models by their primary keys.
findOrFail<TModel extends OrmEntity>(Object id, {String? connection}) Future<TModel>
Find a model by its primary key, throws if not found.
first<TModel extends OrmEntity>({String? connection}) Future<TModel?>
Get the first model matching the query, or null.
firstOrCreate<TModel extends Model<TModel>>(Map<String, dynamic> attributes, {Map<String, dynamic> values = const {}, String? connection}) Future<TModel>
Get first model or create and persist it.
firstOrFail<TModel extends OrmEntity>({String? connection}) Future<TModel>
Get the first model matching the query, or throw.
firstOrNew<TModel extends Model<TModel>>(Map<String, dynamic> attributes, {Map<String, dynamic> values = const {}, String? connection}) Future<TModel>
Get first model or create new (but don't persist yet).
insert<TModel extends OrmEntity>(List<Map<String, dynamic>> records, {String? connection}) Future<void>
Inserts multiple records without returning model instances.
isIgnoringTimestamps(Type modelType, {String? modelName}) bool
Returns true if the given model type is ignoring timestamps.
isIgnoringTouch(Type modelType, {String? modelName}) bool
Returns true if the given model type is ignoring touches.
limit<TModel extends OrmEntity>(int count, {String? connection}) Query<TModel>
Starts a query with a limit clause.
loadRelations<T extends Model<T>>(Iterable<T> models, String relation, [PredicateCallback<OrmEntity>? constraint]) Future<void>
Lazily loads a relation on multiple models efficiently.
loadRelationsMany<T extends Model<T>>(Iterable<T> models, Iterable<String> relations) Future<void>
Lazily loads multiple relations on multiple models efficiently.
loadRelationsMissing<T extends Model<T>>(Iterable<T> models, Iterable<String> relations) Future<void>
Lazily loads relations on multiple models if not already loaded.
noneExist<TModel extends OrmEntity>({String? connection}) Future<bool>
Check if no models exist in the database.
orderBy<TModel extends OrmEntity>(String column, {String direction = 'asc', String? connection}) Query<TModel>
Starts a query with an orderBy clause.
query<TModel extends OrmEntity>({String? connection}) Query<TModel>
Starts a Query for TModel, honoring the model's preferred connection.
repository<TModel extends OrmEntity>({String? connection}) Repository<TModel>
Creates a Repository for TModel, honoring the model's preferred connection.
sole<TModel extends OrmEntity>({String? connection}) Future<TModel>
Get a single model and throw if zero or more than one result is found.
unbindConnectionResolver() → void
Unbinds the global resolver factory (useful for tests).
updateOrCreate<TModel extends Model<TModel>>(Map<String, dynamic> attributes, Map<String, dynamic> values, {String? connection}) Future<TModel>
Update existing model or create new one.
upsert<TModel extends Model<TModel>>(Map<String, dynamic> attributes, {List<String>? uniqueBy, List<String>? updateColumns, String? connection}) Future<TModel>
Upserts a single record (insert or update on conflict).
upsertMany<TModel extends Model<TModel>>(List<Map<String, dynamic>> records, {List<String>? uniqueBy, List<String>? updateColumns, String? connection}) Future<List<TModel>>
Upserts multiple records (insert or update on conflict).
where<TModel extends OrmEntity>(String column, String operator, dynamic value, {String? connection}) Query<TModel>
Starts a query with a where clause.
whereIn<TModel extends OrmEntity>(String column, List values, {String? connection}) Query<TModel>
Starts a query with a whereIn clause.
withoutTimestampsOn<T>(Iterable<Type> models, T callback()) → T
Disable timestamps for the given model classes during the callback scope.
withoutTouchingOn<T>(Iterable<Type> models, T callback()) → T
Disable touching for the given model classes during the callback scope.