updatePivot method

Future<int> updatePivot(
  1. String relName,
  2. dynamic relatedId,
  3. Map<String, dynamic> values
)

Update pivot data between this model and a related model. Updates DB immediately. Does NOT reload models.

Implementation

Future<int> updatePivot(
  String relName,
  dynamic relatedId,
  Map<String, dynamic> values,
) async {
  final rel = relations()[relName];

  if (rel == null) {
    throw Exception(
      "Relation '$relName' is not defined on $runtimeType."
    );
  }

  if (rel.type != RelationType.belongsToMany) {
    throw Exception(
      "updatePivot() can only be used with belongsToMany relations. "
      "'$relName' is ${rel.type}."
    );
  }

  if (values.isEmpty) {
    return 0;
  }

  final parentId = toMap()[primaryKey];
  if (parentId == null) {
    throw Exception(
      "Cannot updatePivot('$relName'): parent model is not saved."
    );
  }

  if (relatedId == null) {
    throw Exception(
      "Cannot updatePivot('$relName'): relatedId is null."
    );
  }

  // 1) Update pivot table
  final affected = await dbService.update(
    rel.pivotTable!,
    values,
    where:
      '${rel.pivotForeignKey} = ? AND ${rel.pivotRelatedKey} = ?',
    params: [parentId, relatedId],
  );

  // 2) Best-effort in-memory sync (Laravel does this implicitly)
  final current = getRelation(relName);
  if (current is List) {
    for (final item in current) {
      final id =
          (item as dynamic).toMap()[rel.child.primaryKey];
      if (id == relatedId) {
        (item as dynamic).pivot ??= {};
        (item as dynamic).pivot!.addAll(values);
        break;
      }
    }
  }

  return affected;
}