describeRelation function

Map<String, Object?> describeRelation(
  1. Relation<Model> relation
)

One relation: its name, type, related model and keys.

Implementation

Map<String, Object?> describeRelation(Relation<Model> relation) {
  final type = relation.runtimeType.toString().split('<').first;
  return {
    'name': relation.name,
    'type': type,
    'related': switch (relation) {
      MorphTo(:final types) => [for (final t in types) modelClassName(t())],
      _ => modelClassName(relation.related),
    },
    ...switch (relation) {
      MorphToMany() => {
        'pivotTable': relation.pivotTable,
        'foreignPivotKey': relation.foreignPivotKey,
        'relatedPivotKey': relation.relatedPivotKey,
        'morphType': relation.morphType,
      },
      BelongsToMany() => {
        'pivotTable': relation.pivotTable,
        'foreignPivotKey': relation.foreignPivotKey,
        'relatedPivotKey': relation.relatedPivotKey,
      },
      MorphMany() => {
        'foreignKey': relation.foreignKey,
        'morphType': relation.morphType,
        'localKey': relation.localKey,
      },
      HasMany() => {
        'foreignKey': relation.foreignKey,
        'localKey': relation.localKey,
      },
      HasManyThrough() => {
        'through': modelClassName(relation.through()),
        'firstKey': relation.firstKey,
        'secondKey': relation.secondKey,
      },
      BelongsTo() => {
        'foreignKey': relation.foreignKey,
        'ownerKey': relation.ownerKey,
      },
      MorphTo() => {
        'foreignKey': relation.foreignKey,
        'morphType': relation.morphType,
      },
      _ => const <String, Object?>{},
    },
  };
}