Skip to content

Commit

Permalink
Fix loopbackio#1795 - Count issue with related models using though model
Browse files Browse the repository at this point in the history
  • Loading branch information
regevbr committed Nov 30, 2019
1 parent a5ba740 commit f281d57
Showing 1 changed file with 42 additions and 2 deletions.
44 changes: 42 additions & 2 deletions lib/scope.js
Original file line number Diff line number Diff line change
Expand Up @@ -517,11 +517,51 @@ function defineScope(cls, targetClass, name, params, methods, options) {
options = {};
}
options = options || {};

// If there is a through model
// run another query to apply filter on relatedModel(targetModel)
// see github.com/strongloop/loopback-datasource-juggler/issues/1795
let scopeOnRelatedModel = false;
let queryRelated;
if (this._scope && this._scope.collect &&
where !== null && typeof where === 'object') {
queryRelated = {
relation: this._scope.collect,
scope: {
where: where,
},
};
where = {};
scopeOnRelatedModel = true;
}
const targetModel = definition.targetModel(this._receiver);
const scoped = (this._scope && this._scope.where) || {};
const filter = mergeQuery({where: scoped}, {where: where || {}});
return targetModel.count(filter.where, options, cb);
if (!scopeOnRelatedModel) {
return targetModel.count(filter.where, options, cb);
}
return targetModel.find(filter, options, function(err, data) {
const relatedModel = targetModel.relations[queryRelated.relation].modelTo;
const keyFrom = targetModel.relations[queryRelated.relation].keyFrom;
const IdKey = idName(relatedModel);

// Merge queryRelated filter and targetId filter
const buildWhere = function() {
return {
and: [
{
[IdKey]: collectTargetIds(data, keyFrom || IdKey),
},
queryRelated.scope.where],
};
};
if (queryRelated.scope.where !== undefined) {
queryRelated.scope.where = buildWhere();
} else {
queryRelated.scope.where = {};
queryRelated.scope.where[IdKey] = collectTargetIds(data, keyFrom || IdKey);
}
return relatedModel.count(queryRelated.scope.where, options, cb);
});
}

return definition;
Expand Down

0 comments on commit f281d57

Please sign in to comment.