detachPivot method
Detach from pivot table by related model ID. Deleted from DB immediately.
Implementation
Future<void> detachPivot(
String relName,
dynamic relatedId,
) async {
final rel = relations()[relName];
if (rel == null) {
throw Exception(
"Relation '$relName' is not defined on $runtimeType."
);
}
if (rel.type != RelationType.belongsToMany) {
throw Exception(
"detachPivotById() can only be used with belongsToMany relations. "
"'$relName' is ${rel.type}."
);
}
final parentId = toMap()[primaryKey];
if (parentId == null) {
throw Exception(
"Cannot detachPivotById('$relName'): parent model is not saved."
);
}
if (relatedId == null) {
throw Exception(
"Cannot detachPivotById('$relName'): relatedId is null."
);
}
await dbService.delete(
rel.pivotTable!,
where:
'${rel.pivotForeignKey} = ? AND ${rel.pivotRelatedKey} = ?',
params: [parentId, relatedId],
);
// Optional: keep in-memory relation consistent if already loaded
final current = getRelation(relName);
if (current is List) {
current.removeWhere(
(e) =>
(e as dynamic).toMap()[rel.child.primaryKey] == relatedId,
);
}
}