diff --git a/lib/src/database/orm/model.dart b/lib/src/database/orm/model.dart index ff0f327..9541ec1 100644 --- a/lib/src/database/orm/model.dart +++ b/lib/src/database/orm/model.dart @@ -701,10 +701,11 @@ abstract class Model extends QueryBuilderImpl { if (!_relationsRegistered) { registerRelations(); _relationsRegistered = true; - final rela = _relations[relation]; - if (rela != null && rela is MorphTo) { - where(rela.morphType, '=', rela.type!); - } + } + + final rela = _relations[relation]; + if (rela != null && rela is MorphTo) { + where(rela.morphType, '=', rela.type!); } _withRelation.add(_RelationQuery(relation, callback)); @@ -712,11 +713,7 @@ abstract class Model extends QueryBuilderImpl { } void _clearWithRelation(_RelationQuery r) { - if (_withRelation.length == 1) { - _withRelation = []; - } else { - _withRelation.remove(r); - } + _withRelation = _withRelation.where((item) => item != r).toList(); } Future _eagerLoadRelation( @@ -731,6 +728,23 @@ abstract class Model extends QueryBuilderImpl { String primaryRelation = wr.first; + List getColumns = ['*']; + final relationParts = primaryRelation.split(':'); + + if (relationParts.length > 1) { + primaryRelation = relationParts.first.trim(); + + final columnsString = relationParts.last.trim(); + + if (columnsString.isNotEmpty) { + getColumns = columnsString + .split(',') + .map((col) => col.trim()) + .where((col) => col.isNotEmpty) + .toList(); + } + } + if (!_relations.containsKey(primaryRelation)) { throw InvalidArgumentException( 'Relation $relation not found in $runtimeType', @@ -774,7 +788,16 @@ abstract class Model extends QueryBuilderImpl { } } } else { - Set ids = models.map((m) => m[rela.localKey]).toSet(); + late final String getLocalKey; + if (rela is BelongsTo) { + getLocalKey = + rela.foreignKey ?? + '${rela.related.runtimeType.toString()}_id'.toLowerCase(); + } else { + getLocalKey = rela.localKey; + } + + Set ids = models.map((m) => m[getLocalKey]).toSet(); if (rela is BelongsToMany) { qb = @@ -796,15 +819,16 @@ abstract class Model extends QueryBuilderImpl { qb = qb.whereIn(rela.foreignKey!, ids.toList()) as Model; } } + late final List> results; + if (wr.length > 1) { wr.removeAt(0); - var results = await qb.include(wr.join('.')).get(); - callBack(rela.match(models, results, primaryRelation)); + results = await qb.include(wr.join('.')).get(getColumns); } else { - var results = await qb.get(); - - callBack(rela.match(models, results, primaryRelation)); + results = await qb.get(getColumns); } + + callBack(rela.match(models, results, primaryRelation)); } } @@ -812,7 +836,9 @@ abstract class Model extends QueryBuilderImpl { List> result, ) async { if (_withRelation.isNotEmpty) { - for (_RelationQuery relation in _withRelation) { + final relationsToLoad = List<_RelationQuery>.from(_withRelation); + + for (_RelationQuery relation in relationsToLoad) { await _eagerLoadRelation(result, relation, (callBackResult) { result = callBackResult; });