load<T extends Model> method

Future<Map<String, dynamic>> load<T extends Model>(
  1. ModelRelationshipType relationship, {
  2. PivotTable<Model, Model>? table,
})

Loads a relationship and returns this model serialized with the related data embedded.

The returned map contains toJson() for the current model plus an additional key for the requested relationship:

  • singular table name for hasOne and belongsToOne
  • plural table name for hasMany and belongsToMany

For belongsToMany, table is required.

Example:

final userWithProfile = await user.load<Profile>(
  ModelRelationshipType.hasOne,
);

final userWithRoles = await user.load<Role>(
  ModelRelationshipType.belongsToMany,
  table: userRolesPivot,
);

Implementation

Future<Map<String, dynamic>> load<T extends Model>(ModelRelationshipType relationship, {PivotTable? table}) async {
  switch(relationship) {

    case ModelRelationshipType.hasOne:
      final sibling = await  hasOne<T>();
      final siblingTable = Model.getTableSingularName<T>();
      return {...toJson(), siblingTable : sibling?.toJson()};

    case ModelRelationshipType.hasMany:
      final siblings = await  hasMany<T>();
      final siblingsTable = Model.getTableName<T>();
      return {...toJson(), siblingsTable : siblings.map((sibling) => sibling.toJson()).toList() };
    case ModelRelationshipType.belongsToOne:
      final sibling = await  belongsToOne<T>();
      final siblingTable = Model.getTableSingularName<T>();
      return {...toJson(), siblingTable : sibling?.toJson()};

    case ModelRelationshipType.belongsToMany:
      if(table == null) {
        throw Exception("pivot table is required for belongsToMany relationships");
      }
      final siblings = await  belongsToMany<T>(table: table );
      final siblingsTable = Model.getTableName<T>();
      return {...toJson(), siblingsTable : siblings.map((sibling) => sibling.toJson()).toList() };
  }

}