diff --git a/.gitignore b/.gitignore index 708939d7..cd4e7b78 100644 --- a/.gitignore +++ b/.gitignore @@ -6,6 +6,7 @@ v8.log .idea .DS_Store .git +.vscode benchmark.js analyse.r docs/html diff --git a/lib/include.js b/lib/include.js index a9824fb9..5219bc7a 100644 --- a/lib/include.js +++ b/lib/include.js @@ -437,8 +437,9 @@ Inclusion.include = function(objects, include, options, cb) { if (polymorphic) { // handle polymorphic hasMany (reverse) in which case we need to filter // by discriminator to filter other types + const throughModel = polymorphic.invert ? relation.modelTo : relation.modelFrom; throughFilter.where[polymorphic.discriminator] = - relation.modelFrom.definition.name; + throughModel.definition.name; } // 1st DB Call of 2-step process. Get through model objects first diff --git a/test/relations.test.js b/test/relations.test.js index d6b23fbe..d7b6e72b 100644 --- a/test/relations.test.js +++ b/test/relations.test.js @@ -6621,4 +6621,35 @@ describe('relations', function() { }).should.throw('Invalid relation name: trigger'); }); }); + + describe('polymorphic hasMany - revert', function() { + before(function(done) { + Picture = db.define('Picture', {name: String}); + Author = db.define('Author', {name: String}); + PictureLink = db.define('PictureLink', {}); + Author.hasMany(Picture, {through: PictureLink, polymorphic: 'imageable', invert: true}); + Picture.hasMany(Author, {through: PictureLink, polymorphic: 'imageable'}); + db.automigrate(['Picture', 'Author', 'PictureLink'], done); + }); + it('should properly query through an inverted relationship', function(done) { + Author.create({name: 'Steve'}, function(err, author) { + if (err) { + return done(err); + } + author.pictures.create({name: 'Steve pic 1'}, function(err, pic) { + if (err) { + return done(err); + } + Author.findOne({include: 'pictures'}, function(err, author) { + if (err) { + return done(err); + } + author.pictures().length.should.eql(1); + author.pictures()[0].name.should.eql('Steve pic 1'); + done(); + }); + }); + }); + }); + }); });