I am using Sequelize for Node and I have Users and items. A user can interact with an item in multiple ways, such as voting, or commending (two different things in this case).
My initial thought was to have two different many to many relationship but Sequelize only has one removeItem call, and I haven't figured out how to specify which.
Plan 2 was to build one many to many table with an extra element "type" so I could specify the kind. I can specify the type when the thing is added. This ran into two problems, one they are forign keys and by default that made the pair unique. I corrected this by removing the constraint manually from the DB, and that seemed to be sufficient (I set an id as primary key autoincrement). Secondly, I cannot seem to figure out how to make the delete specify where type = the type I want.
Code:
To build the table:
var UserActions = sequelize.define('userActions', {
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true
},
type: DataTypes.STRING
});
To remove the item:
models.Item.findOne({where: {id : params.itemID}}).then(function (video){
models.User.findOne({where: {id : params.itemID}}).then(function (user){
if(params.applaud == "true") {
console.log("Add applaud");
user.addItem(video,{type:"commend"});
} else {
user.removeItem(item,{where: {type:"commend"}});
console.log("Remove, Commendation");
}
res.json({'response' : 'Success'});
});
});
The issue is this will delete all interactions between the item and the user, when I want it to only delete the commendation.
How do I best manage multiple many to many relationships between the same two tables in Sequelize?
OK I figured it out.
On the association you have to specify an alias via 'as'
User.belongsToMany(models.Item, {through: 'votes', as: 'votes'});
User.belongsToMany(models.Item, {through: 'commend', as: 'commend'});
Then you can add query with:
models.Item.findOne({where: {id: item.id},
include: [{
model: models.User,
as: 'votes'
}]
})
You can add with:
user.addVote(item);
or
user.addCommend(item);
And delete with:
user.removeVote(item);
or
user.removeCommend(item)
And it works as desired.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With