Skip to content

Commit

Permalink
Fix polymorphic hasMany inverse relation (#1621)
Browse files Browse the repository at this point in the history
* Polymorphic hasMany inverse relation

* rename test suit to eslint error
  • Loading branch information
iamraphson authored and jannyHou committed Aug 12, 2019
1 parent ac95582 commit 814c55c
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 1 deletion.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ v8.log
.idea
.DS_Store
.git
.vscode
benchmark.js
analyse.r
docs/html
Expand Down
3 changes: 2 additions & 1 deletion lib/include.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
31 changes: 31 additions & 0 deletions test/relations.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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();
});
});
});
});
});
});

0 comments on commit 814c55c

Please sign in to comment.