matchMorphOneOrMany method

List<Map<String, dynamic>> matchMorphOneOrMany(
  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 one related morph model to parents (for hasOne polymorphic relation). Only includes results where typeKey equals expectedType and returns only the first matching result.

Implementation

List<Map<String, dynamic>> matchMorphOneOrMany(
  List<Map<String, dynamic>> models,
  List<Map<String, dynamic>> results,
  String relation,
  String parentKey,
  String relatedIdKey,
  String typeKey,
  String expectedType,
) {
  Map<String, 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] = 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] = null;
    }
    return cloneModel;
  }).toList();

  return models;
}