dissociate method
Dissociates a belongsTo parent model and clears the foreign key.
This is a convenient helper that:
- Sets the foreign key field to null
- Removes the parent from the relation cache
- Marks the relation as not loaded
Example:
final post = Post(id: 1, authorId: 5, title: 'Hello');
await post.dissociate('author');
// post.authorId is now null
// post.author is now null
Implementation
Future<TModel> dissociate(String relationName) async {
final def = expectDefinition();
final relationDef = def.relations.cast<RelationDefinition?>().firstWhere(
(r) => r?.name == relationName,
orElse: () => null,
);
if (relationDef == null) {
throw ArgumentError(
'Relation "$relationName" not found on ${def.modelName}',
);
}
if (relationDef.kind != RelationKind.belongsTo) {
throw ArgumentError(
'dissociate() can only be used with belongsTo relations. '
'Relation "$relationName" is ${relationDef.kind}',
);
}
// Find the foreign key field and nullify it
final foreignKeyName = relationDef.foreignKey;
final field = def.fields.firstWhere(
(f) => f.columnName == foreignKeyName || f.name == foreignKeyName,
);
_asAttributes.setAttribute(field.columnName, null);
// Remove from relation cache
_asRelations.unsetRelation(relationName);
return _self();
}