dissociate method

Future<OrmMigrationRecord> dissociate(
  1. String relationName
)
inherited

Dissociates a belongsTo parent model and clears the foreign key.

This is a convenient helper that:

  1. Sets the foreign key field to null
  2. Removes the parent from the relation cache
  3. 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();
}