Skip to content

Commit

Permalink
Fixes setAssociation with scope (sequelize#7159)
Browse files Browse the repository at this point in the history
* Fixes setAssociation with scope

* Fixes style
  • Loading branch information
pola88 authored and janmeier committed Feb 8, 2017
1 parent e22ce18 commit 8cbd375
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
2 changes: 2 additions & 0 deletions lib/associations/belongs-to-many.js
Original file line number Diff line number Diff line change
Expand Up @@ -583,6 +583,8 @@ class BelongsToMany extends Association {
}

where[identifier] = sourceInstance.get(sourceKey);
_.assign(where, association.through.scope);

return association.through.model.findAll(_.defaults({where, raw: true}, options)).then(currentRows => {
const obsoleteAssociations = [];
const promises = [];
Expand Down
50 changes: 50 additions & 0 deletions test/integration/associations/belongs-to-many.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -616,6 +616,56 @@ describe(Support.getTestDialectTeaser('BelongsToMany'), function() {
expect(tasks[0].title).to.equal('wat');
});
});

it('using scope to set associations', function() {
var ItemTag = this.sequelize.define('ItemTag', {
id : { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
tag_id: { type: DataTypes.INTEGER, unique: false },
taggable: { type: DataTypes.STRING },
taggable_id: { type: DataTypes.INTEGER, unique: false }
}),
Tag = this.sequelize.define('Tag', {
id : { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
name: DataTypes.STRING
}),
Comment = this.sequelize.define('Comment', {
id : { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
name: DataTypes.STRING
}),
Post = this.sequelize.define('Post', {
id : { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
name: DataTypes.STRING
});

Post.belongsToMany(Tag, {
through: { model: ItemTag, unique: false, scope: { taggable: 'post' } },
foreignKey: 'taggable_id'
});

Comment.belongsToMany(Tag, {
through: { model: ItemTag, unique: false, scope: { taggable: 'comment' } },
foreignKey: 'taggable_id'
});

return this.sequelize.sync({ force: true }).then(function() {
return Promise.all([
Post.create({ name: 'post1' }),
Comment.create({ name: 'comment1' }),
Tag.create({ name: 'tag1' })
]);
}).bind({}).spread(function(post, comment, tag) {
this.post = post;
this.comment = comment;
this.tag = tag;
return this.post.setTags([this.tag]);
}).then(function() {
return this.comment.setTags([this.tag]);
}).then(function() {
return this.comment.getTags();
}).then(function(_tags) {
expect(_tags).to.have.length(1);
});
});
});

describe('createAssociations', function() {
Expand Down

0 comments on commit 8cbd375

Please sign in to comment.