attach method

void attach(
  1. String relName,
  2. RelationalModel<RelationalModel> child
)

HAS ONE / HAS MANY: parent.attach('hosts', child), sets FK on child, requires save()

Implementation

void attach(String relName, RelationalModel child)
{
  final rel = relations()[relName];
  if (rel == null ||
      (rel.type != RelationType.hasOne && rel.type != RelationType.hasMany)) {
    throw Exception("$relName is not a hasOne/hasMany relation.");
  }

  final fk = rel.foreignKey; // e.g. publisher_id on HOST model

  // Resolve local key (parent primary key or custom)
  final localKeyValue = (this as dynamic).toMap()[rel.resolveLocalKey(this as T)];

  if (localKeyValue == null) {
    throw Exception("Cannot attach child: parent has no primary key.");
  }

  // Queue child foreign key update, do NOT save
  child.setAttribute(fk, localKeyValue);

  // Store related child in memory (eager-loaded relation)
  if (rel.type == RelationType.hasOne) {
    setRelation(relName, child);
  } else {
    final current = (getRelation(relName) ?? []) as List<dynamic>;
    current.add(child);
    setRelation(relName, current);
  }
}