createManyRelation<TRelated extends Model<TRelated>> method

Future<List<TRelated>> createManyRelation<TRelated extends Model<TRelated>>(
  1. String relationName,
  2. List<Object> attributesList
)
inherited

Creates multiple related models through a hasMany relationship.

Each item in attributesList accepts:

  • A tracked model instance (TRelated).
  • An InsertDto or UpdateDto instance.
  • A Map<String, Object?> containing field/column values.

Example:

final author = await Author.query().find(1);
final posts = await author.createManyRelation<Post>('posts', [
  {'title': 'Post 1', 'published_at': DateTime.now()},
  {'title': 'Post 2', 'published_at': DateTime.now()},
]);

// Using DTOs:
final posts2 = await author.createManyRelation<Post>('posts', [
  PostInsertDto(title: 'DTO 1', publishedAt: DateTime.now()),
  PostInsertDto(title: 'DTO 2', publishedAt: DateTime.now()),
]);

Implementation

Future<List<TRelated>> createManyRelation<TRelated extends Model<TRelated>>(
  String relationName,
  List<Object> attributesList,
) async {
  final def = expectDefinition();

  final relationDef = def.relations.cast<RelationDefinition?>().firstWhere(
    (r) => r?.name == relationName,
    orElse: () => null,
  );

  if (relationDef == null) {
    throw ArgumentError(
      'Relation "$relationName" not found on ${def.modelName}',
    );
  }

  if (relationDef.kind != RelationKind.hasMany) {
    throw ArgumentError(
      'createManyRelation() can only be used with hasMany relations. '
      'Relation "$relationName" is ${relationDef.kind}',
    );
  }

  final results = <TRelated>[];
  for (final attributes in attributesList) {
    results.add(await createRelation<TRelated>(relationName, attributes));
  }

  return results;
}