@@ -431,11 +431,51 @@ function defineScope(cls, targetClass, name, params, methods, options) {
431
431
options = { } ;
432
432
}
433
433
options = options || { } ;
434
-
434
+ // If there is a through model
435
+ // run another query to apply filter on relatedModel(targetModel)
436
+ // see github.com/strongloop/loopback-datasource-juggler/issues/1795
437
+ let scopeOnRelatedModel = false ;
438
+ let queryRelated ;
439
+ if ( this . _scope && this . _scope . collect &&
440
+ where !== null && typeof where === 'object' ) {
441
+ queryRelated = {
442
+ relation : this . _scope . collect ,
443
+ scope : {
444
+ where : where ,
445
+ } ,
446
+ } ;
447
+ where = { } ;
448
+ scopeOnRelatedModel = true ;
449
+ }
435
450
const targetModel = definition . targetModel ( this . _receiver ) ;
436
451
const scoped = ( this . _scope && this . _scope . where ) || { } ;
437
452
const filter = mergeQuery ( { where : scoped } , { where : where || { } } ) ;
438
- return targetModel . destroyAll ( filter . where , options , cb ) ;
453
+ if ( ! scopeOnRelatedModel ) {
454
+ return targetModel . destroyAll ( filter . where , options , cb ) ;
455
+ }
456
+ return targetModel . find ( filter , options , function ( err , findData ) {
457
+ const relatedModel = targetModel . relations [ queryRelated . relation ] . modelTo ;
458
+ const keyFrom = targetModel . relations [ queryRelated . relation ] . keyFrom ;
459
+ const IdKey = idName ( relatedModel ) ;
460
+
461
+ // Merge queryRelated filter and targetId filter
462
+ const buildWhere = function ( ) {
463
+ return {
464
+ and : [
465
+ {
466
+ [ IdKey ] : collectTargetIds ( findData , keyFrom || IdKey ) ,
467
+ } ,
468
+ queryRelated . scope . where ] ,
469
+ } ;
470
+ } ;
471
+ if ( queryRelated . scope . where !== undefined ) {
472
+ queryRelated . scope . where = buildWhere ( ) ;
473
+ } else {
474
+ queryRelated . scope . where = { } ;
475
+ queryRelated . scope . where [ IdKey ] = collectTargetIds ( findData , keyFrom || IdKey ) ;
476
+ }
477
+ return relatedModel . destroyAll ( queryRelated . scope . where , options , cb ) ;
478
+ } ) ;
439
479
}
440
480
441
481
function updateAll ( where , data , options , cb ) {
0 commit comments