hasOne<T extends Model> method

Future<T?> hasOne<T extends Model>({
  1. DatabaseDisk disk = Model.defaultDisk,
})

Resolves a one-to-one related model.

The related model is looked up using the current model's identifier and conventional foreign-key naming for the selected disk.

Returns the related model when found, otherwise null.

Example:

final profile = await user.hasOne<Profile>();
if (profile != null) {
  print(profile.toJson());
}

Implementation

Future<T?> hasOne<T extends Model>({DatabaseDisk disk = Model.defaultDisk}) async {
  try {
    final foreignTableSingular = getInstanceTableSingularName();
    final data = toMetaJson();

    switch (disk) {
      case DatabaseDisk.file:
      case DatabaseDisk.s3:
        final foreignUuidKey = "${foreignTableSingular}_uuid";
        return Model.firstWhere<T>(field: foreignUuidKey, value: data['uuid'], disk: disk);

      case DatabaseDisk.sqlite:
      case DatabaseDisk.pgsql:
        final foreignIdKey = "${foreignTableSingular}_id";
        return Model.firstWhere<T>(field: foreignIdKey, value: data['id'], disk: disk);
    }
  } catch (e,stack) {
    App().archeryLogger.error("Error resolving hasOne", {"origin": "ext ModelRelationships hasOne", "error": e.toString(), "stack": stack.toString()});
    return null;
  }
}