不要怂,就是干,撸起袖子干!

Commit 7fa00e0f by elasticsearcher Committed by Jan Aagaard Meier

Fixes creation of polymorphic belongsToMany associations in one step #7159 (#7181)

1 parent 98abec30
......@@ -729,6 +729,8 @@ Instance.prototype.save = function(options) {
var values = {};
values[include.association.foreignKey] = self.get(self.Model.primaryKeyAttribute, {raw: true});
values[include.association.otherKey] = instance.get(instance.Model.primaryKeyAttribute, {raw: true});
// Include values defined in the scope of the association
_.assign(values, include.association.through.scope);
return include.association.throughModel.create(values, includeOptions);
});
} else {
......
......@@ -268,6 +268,106 @@ describe(Support.getTestDialectTeaser('Model'), function() {
});
});
it('should create data for polymorphic BelongsToMany relations', function () {
var Post = this.sequelize.define('Post', {
title: DataTypes.STRING
}, {
tableName: 'posts',
underscored: true
});
var Tag = this.sequelize.define('Tag', {
name: DataTypes.STRING,
}, {
tableName: 'tags',
underscored: true
});
var ItemTag = this.sequelize.define('ItemTag', {
tag_id: {
type: DataTypes.INTEGER,
references: {
model: 'tags',
key: 'id'
}
},
taggable_id: {
type: DataTypes.INTEGER,
references: null
},
taggable: {
type: DataTypes.STRING,
},
}, {
tableName: 'item_tag',
underscored: true
});
Post.belongsToMany(Tag, {
as: 'tags',
foreignKey: 'taggable_id',
constraints: false,
through: {
model: ItemTag,
scope: {
taggable: 'post'
}
}
});
Tag.belongsToMany(Post, {
as: 'posts',
foreignKey: 'tag_id',
constraints: false,
through: {
model: ItemTag,
scope: {
taggable: 'post'
}
}
});
return this.sequelize.sync({ force: true }).then(function () {
return Post.create({
title: 'Polymorphic Associations',
tags: [
{
name: 'polymorphic'
},
{
name: 'associations'
}
]
}, {
include: [{
model: Tag,
as: 'tags',
through: {
model: ItemTag
}
}]
}
);
}).then(function (savedPost) {
// The saved post should include the two tags
expect(savedPost.tags.length).to.equal(2);
// The saved post should be able to retrieve the two tags
// using the convenience accessor methods
return savedPost.getTags();
}).then(function (savedTags) {
// All nested tags should be returned
expect(savedTags.length).to.equal(2);
}).then(function () {
return ItemTag.findAll();
}).then(function (itemTags) {
// Two "through" models should be created
expect(itemTags.length).to.equal(2);
// And their polymorphic field should be correctly set to 'post'
expect(itemTags[0].taggable).to.equal('post');
expect(itemTags[1].taggable).to.equal('post');
});
});
it('should create data for BelongsToMany relations with alias', function() {
var User = this.sequelize.define('User', {
username: DataTypes.STRING
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!