associate method

void associate(
  1. String relName,
  2. RelationalModel<RelationalModel> parent
)

Implementation

void associate(String relName, RelationalModel parent)
{
  final rel = relations()[relName];
  if (rel == null || rel.type != RelationType.belongsTo) {
    throw Exception("$relName is not a belongsTo relation.");
  }

  final fk = rel.foreignKey;     // e.g. publisher_uuid, publisher_id
  final pk = parent.primaryKey;  // child.parentID = parent.primaryKey
  final parentId = parent.toMap()[pk];

  if (parentId == null) {
    throw Exception("Cannot associate: parent has no primary key.");
  }

  // Queue FK change, but do NOT touch DB or rebuild object
  setAttribute(fk, parentId);

  // Keep object available for eager loaded memory reads
  setRelation(relName, parent);
}