@@ -500,10 +500,49 @@ function defineScope(cls, targetClass, name, params, methods, options) {
500
500
options = { } ;
501
501
}
502
502
options = options || { } ;
503
+ // If there is a through model
504
+ // run another query to apply filter on relatedModel(targetModel)
505
+ // see github.com/strongloop/loopback-datasource-juggler/issues/1795
506
+ let scopeOnRelatedModel = false ;
507
+ let queryRelated ;
508
+ if ( this . _scope && this . _scope . collect &&
509
+ filter && filter . where !== null && typeof filter . where === 'object' ) {
510
+ queryRelated = {
511
+ relation : this . _scope . collect ,
512
+ scope : filter ,
513
+ } ;
514
+ filter = { } ;
515
+ scopeOnRelatedModel = true ;
516
+ }
503
517
const targetModel = definition . targetModel ( this . _receiver ) ;
504
518
const scoped = ( this . _scope && this . _scope . where ) || { } ;
505
519
filter = mergeQuery ( { where : scoped } , filter || { } ) ;
506
- return targetModel . findOne ( filter , options , cb ) ;
520
+ if ( ! scopeOnRelatedModel ) {
521
+ return targetModel . findOne ( filter , options , cb ) ;
522
+ }
523
+ return targetModel . find ( filter , options , function ( err , data ) {
524
+ const relatedModel = targetModel . relations [ queryRelated . relation ] . modelTo ;
525
+ const keyFrom = targetModel . relations [ queryRelated . relation ] . keyFrom ;
526
+ const IdKey = idName ( relatedModel ) ;
527
+
528
+ // Merge queryRelated filter and targetId filter
529
+ const buildWhere = function ( ) {
530
+ return {
531
+ and : [
532
+ {
533
+ [ IdKey ] : collectTargetIds ( data , keyFrom || IdKey ) ,
534
+ } ,
535
+ queryRelated . scope . where ] ,
536
+ } ;
537
+ } ;
538
+ if ( queryRelated . scope . where !== undefined ) {
539
+ queryRelated . scope . where = buildWhere ( ) ;
540
+ } else {
541
+ queryRelated . scope . where = { } ;
542
+ queryRelated . scope . where [ IdKey ] = collectTargetIds ( data , keyFrom || IdKey ) ;
543
+ }
544
+ return relatedModel . findOne ( queryRelated . scope , options , cb ) ;
545
+ } ) ;
507
546
}
508
547
509
548
function count ( where , options , cb ) {
0 commit comments