refresh method

Future<OrmMigrationRecord> refresh({
  1. bool withTrashed = false,
  2. Iterable<String>? withRelations,
})
inherited

Reloads the latest row from the database, optionally including trashed.

The withRelations parameter allows you to specify which relations should be eagerly loaded when refreshing the model.

Example:

await user.refresh(withRelations: ['posts', 'comments']);

Implementation

Future<TModel> refresh({
  bool withTrashed = false,
  Iterable<String>? withRelations,
}) async {
  final def = expectDefinition();
  final resolver = _resolveResolverFor(def);
  final pk = def.primaryKeyField;
  if (pk == null) {
    throw StateError(
      'Model ${def.modelName} must declare a primary key to refresh.',
    );
  }
  final key = _primaryKeyValue(def);
  if (key == null) {
    throw StateError(
      'Model ${def.modelName} is missing primary key ${pk.name}.',
    );
  }
  var builder = _requireQueryContext(resolver).queryFromDefinition(def);
  if (withTrashed && def.usesSoftDeletes) {
    builder = builder.withTrashed();
  }
  // Eager load relations if specified
  if (withRelations != null) {
    for (final relation in withRelations) {
      builder = builder.withRelation(relation);
    }
  }
  final fresh = await builder.whereEquals(pk.name, key).firstOrFail(key: key);
  _syncFrom(fresh, def, resolver);
  // Sync relations from the fresh model if any were loaded
  if (withRelations != null && withRelations.isNotEmpty) {
    for (final relationName in withRelations) {
      final freshAsRelations = (fresh as Model<TModel>)._asRelations;
      if (freshAsRelations.relationLoaded(relationName)) {
        final value = freshAsRelations.loadedRelations[relationName];
        _asRelations.setRelation(relationName, value);
      }
    }
  }
  return _self();
}