2016-11-20 67 views
3

我有以下結構:Sequelize許多一對多表具有相同的外鍵是壓倒價值

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 }); 

同一個用戶,應該能夠使倍數意見相同的柱。 但是,當我執行

post.addPostUserComment(currentUserId, {comment: "teste"}) 

如果我已經有了這個職位由currentUser做了一個評論,它覆蓋的時候,它應該創建一個新的行中的數據庫「註釋」的價值。

方言:mysql的 Sequelize版本:3.24.2〜

我做錯什麼了嗎?

回答

2

belongsToMany意味着多對多關係,它確保一個帖子將通過PostComment中的一行與一個用戶連接。它不違背多對多的關係原則,因爲在PostComment中post也可以通過另一行與其他用戶有關係。所以你的情況時,用戶可以將多個註釋添加到一個職位,你應該定義下列協會:

Post.hasMany(PostComment);

User.hasMany(PostComment);

,並添加註釋會看起來像這樣:

post.addPostComment({userId: currentUserId, comment: 'test'}) 
+0

我不得不放棄並按照自己的方式去做,我能夠創建新的實例,但是我無法全部選擇它們。你的解決方案爲我工作。謝謝 –

0

我最終在做

Post.belongsToMany(User, {as: 'postUserComment', through: {model: models.PostComment, unique: false}, foreignKey: 'idPost'}); 

User.belongsToMany(Post, {through: {model: models.PostComment, unique: false}, foreignKey: 'idUserComment'}); 

我現在可以創建多個評論。 我在挑選它們時遇到了一些麻煩,但這是我相信另一個問題的原因。

+0

我不得不通過@ tilov-yrys的方式來做,因爲我能夠創建新的實例但不選擇它們 –