loadCount method

Future<OrmMigrationRecord> loadCount(
  1. String relation, {
  2. String? alias,
  3. PredicateCallback<OrmEntity>? constraint,
})
inherited

Lazily loads the count of a relation.

Stores the count as an attribute with the suffix _count.

Example:

await post.loadCount('comments');
print(post.getAttribute<int>('comments_count')); // e.g., 5

With custom alias:

await post.loadCount('comments', alias: 'total_comments');
print(post.getAttribute<int>('total_comments'));

Implementation

Future<TModel> loadCount(
  String relation, {
  String? alias,
  PredicateCallback<OrmEntity>? constraint,
}) async {
  if (ModelRelations.preventsLazyLoading) {
    throw LazyLoadingViolationException(runtimeType, relation);
  }

  final def = expectDefinition();
  final resolver = _resolveResolverFor(def);
  final context = _requireQueryContext(resolver);

  // Find the relation definition
  final relationDef = def.relations.cast<RelationDefinition?>().firstWhere(
    (r) => r?.name == relation,
    orElse: () => null,
  );

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

  final countAlias = alias ?? '${relation}_count';

  // Build a query for this model with withCount
  final query = context.queryFromDefinition(def);

  // Get the primary key value
  final pkField = def.primaryKeyField;
  if (pkField == null) {
    throw StateError('Cannot load count on model without primary key');
  }

  final pkValue = _asAttributes.getAttribute(pkField.columnName);
  if (pkValue == null) {
    throw StateError('Cannot load count on model without primary key value');
  }

  // Query for this specific model with count
  query.where(pkField.columnName, pkValue);
  query.withCount(relation, alias: countAlias, constraint: constraint);

  final rows = await query.get();
  if (rows.isNotEmpty) {
    final result = rows.first;
    final count = result._asAttributes.getAttribute<int>(countAlias) ?? 0;
    _asAttributes.setAttribute(countAlias, count);
  }

  return _self();
}