fetch method

Future<List<T>?> fetch()

Implementation

Future<List<T>?> fetch() async {
  if (_isLoaded) {
    return _value;
  }

  final thisLocalKeyValue = _parent.toDatumMap()[thisLocalKey];
  if (thisLocalKeyValue == null) {
    return [];
  }

  // Get the manager for the pivot entity
  final pivotManager = Datum.managerByType(pivotEntity.runtimeType);

  // Query the pivot entity to find related pivot entities
  final pivotEntities = await pivotManager.query(
    DatumQuery(filters: [Filter(thisForeignKey, FilterOperator.equals, thisLocalKeyValue)]),
    source: DataSource.local,
    userId: _parent.userId,
  );

  // Extract the foreign keys of the related entities from the pivot entities
  final otherForeignKeys = pivotEntities.map((e) => e.toDatumMap()[otherForeignKey]).nonNulls.toList();

  if (otherForeignKeys.isEmpty) {
    _value = [];
    _isLoaded = true;
    return _value;
  }

  // Get the manager for the target entity type
  final relatedManager = getRelatedManager();

  // Query the target entity manager to get the related entities
  final related = await relatedManager.query(
    DatumQuery(filters: [Filter('id', FilterOperator.isIn, otherForeignKeys)]),
    source: DataSource.local,
    userId: _parent.userId,
  );

  _value = related;
  _isLoaded = true;
  return related;
}