Model Attributes
Ormed models support attribute metadata that affects:
- Mass assignment (
fill,fillIfAbsent,forceFill) - Serialization (
toArray,toJson) - Casting (see Models → Casting)
Tracked models
These APIs are designed for tracked models (the generated $Model types) and instances returned by queries. Plain user-defined model instances are immutable and typically not used for mass assignment.
Define metadata
Attribute metadata can be declared at the model level, and optionally overridden per-field.
(
table: 'accounts',
fillable: ['email', 'name'],
guarded: ['is_admin'],
hidden: ['password_hash'],
visible: ['password_hash'],
)
class Account extends Model<Account> {
const Account({
required this.id,
required this.email,
required this.passwordHash,
this.name,
this.isAdmin = false,
});
(isPrimaryKey: true, autoIncrement: true)
final int id;
final String email;
(columnName: 'password_hash')
final String passwordHash;
final String? name;
(columnName: 'is_admin', guarded: true)
final bool isAdmin;
}
Mass assignment
Mass assignment takes a Map<String, Object?> keyed by column names and applies fillable/guarded rules.
void massAssignmentExample() {
final account = $Account(id: 1, email: 'a@example.com', passwordHash: 'hash');
// Only fillable columns are applied; guarded columns are discarded.
account.fill({'email': 'new@example.com', 'is_admin': true});
// Enable strict mode to throw instead of silently discarding.
try {
account.fill({'is_admin': true}, strict: true);
} on MassAssignmentException {
// Handle mass assignment failures.
}
// Bypass guards for trusted code paths.
account.forceFill({'is_admin': true});
}
Notes:
fill(...)defaults tostrict: false(guarded keys are discarded).- Set
strict: trueto throw aMassAssignmentExceptionwhen a guarded key is present. - Use
forceFill(...)only for trusted/internal flows.
Serialization (hidden / visible)
toArray() / toJson() honor hidden by default. To include hidden values you must set includeHidden: true, and the column must also be listed in visible.
Map<String, Object?> serializationExample() {
final account = $Account(id: 1, email: 'a@example.com', passwordHash: 'hash');
// Hidden columns are excluded.
final safe = account.toArray();
// Hidden columns can be included, but only when they're explicitly visible.
final internal = account.toArray(includeHidden: true);
return {'safe': safe, 'internal': internal};
}