matchMorphMany method

List<Map<String, dynamic>> matchMorphMany(
  1. List<Map<String, dynamic>> models,
  2. List<Map<String, dynamic>> results,
  3. String relation,
  4. String parentKey,
  5. String relatedIdKey,
  6. String typeKey,
  7. String expectedType,
)

Match many related morph models to parents. Only includes results where the morph type (at column typeKey) equals expectedType.

Implementation

List<Map<String, dynamic>> matchMorphMany(
  List<Map<String, dynamic>> models,
  List<Map<String, dynamic>> results,
  String relation,
  String parentKey,
  String relatedIdKey,
  String typeKey,
  String expectedType,
) {
  Map<String, List<Map<String, dynamic>>> dictionary = {};
  final type = expectedType.toLowerCase();
  for (var result in results) {
    if (result[typeKey]?.toString().toLowerCase() == type) {
      String key = result[relatedIdKey].toString();
      if (!dictionary.containsKey(key)) {
        dictionary[key] = [];
      }
      dictionary[key]!.add(result);
    }
  }

  models = models.map((model) {
    String key = model[parentKey].toString();
    Map<String, dynamic> cloneModel = Map.from(model);
    if (dictionary.containsKey(key)) {
      cloneModel[relation] = dictionary[key];
    } else {
      cloneModel[relation] = <Map<String, dynamic>>[];
    }
    return cloneModel;
  }).toList();

  return models;
}