Reputation: 782
I have the following structure:
var User = sequelize.define('user', {
name: DataTypes.STRING
});
var Post = sequelize.define('post', {
text: DataTypes.STRING
});
var PostComment = sequelize.define('postComment', {
id: {
type: DataTypes.BIGINT,
primaryKey: true,
autoIncrement: true
},
comment: DataTypes.TEXT
});
Post.belongsToMany(User, { as: 'postUserComment', through: PostComment });
User.belongsToMany(Post, { through: PostComment });
The same user, should be able to make multiples comments to the same post. But when i execute
post.addPostUserComment(currentUserId, {comment: "teste"})
If i already have a comment to this post made by the currentUser, it override it's "comment" value in the database when it should create a new row.
Dialect: mysql Sequelize version: ~3.24.2
Am i doing something wrong?
Upvotes: 4
Views: 1650
Reputation: 782
I end up doing
Post.belongsToMany(User, {as: 'postUserComment', through: {model: models.PostComment, unique: false}, foreignKey: 'idPost'});
User.belongsToMany(Post, {through: {model: models.PostComment, unique: false}, foreignKey: 'idUserComment'});
I am able to create multiples comments now. I am having a little trouble to select them all, but it's something to another issue i belive.
Upvotes: 0
Reputation: 2775
belongsToMany
means many-to-many relation, it ensure that one post will join with one user through only one row in PostComment. It doesn't violate many-to-many relation principle, because post can also has relation with other user through another row in PostComment. So in your case when user is able to add multiple comments to one post you should define following associations:
Post.hasMany(PostComment);
User.hasMany(PostComment);
and adding comments will looks like this:
post.addPostComment({userId: currentUserId, comment: 'test'})
Upvotes: 2