loadExists method
Lazily loads the existence of a relation.
Stores the boolean result as an attribute with the suffix _exists.
Example:
await post.loadExists('comments');
if (post.getAttribute<bool>('comments_exists') == true) {
print('Post has comments');
}
Implementation
Future<TModel> loadExists(
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 existsAlias = alias ?? '${relation}_exists';
// Build a query for this model with withExists
final query = context.queryFromDefinition(def);
// Get the primary key value
final pkField = def.primaryKeyField;
if (pkField == null) {
throw StateError('Cannot load exists on model without primary key');
}
final pkValue = _asAttributes.getAttribute(pkField.columnName);
if (pkValue == null) {
throw StateError('Cannot load exists on model without primary key value');
}
// Query for this specific model with exists
final queryWithAggregate = query
.where(pkField.columnName, pkValue)
.withExists(relation, alias: existsAlias, constraint: constraint);
final rows = await queryWithAggregate.get();
if (rows.isNotEmpty) {
final result = rows.first;
// SQL returns 1/0 for EXISTS, convert to boolean
final value = result._asAttributes.getAttribute(existsAlias);
final exists = value == true || value == 1;
_asAttributes.setAttribute(existsAlias, exists);
}
return _self();
}