我正在为一个项目实施一个类似的系统。我需要一些帮助。
基本上我有两个按钮(upvote和downvote),它们调用我的函数并给出线程的id、用户名投票和投票(1或-1)。
addPositiveorNegativeLikes = function(thread_id, username, vote) {
sequelize.query('INSERT INTO Likes (thread_id, userId, vote, createdAt, updatedAt)
VALUES((?), (SELECT id FROM Users WHERE username=(?)), (?), (?), (?))
ON DUPLICATE KEY UPDATE thread_id=(?), userId=(SELECT id FROM Users WHERE username=(?))',{
replacements: [thread_id, username, vote, new Date(), new Date(), thread_id, username]
})
}
但现在在我的likes表中,虽然thread\u id和userid都是主键,但插入了多个重复的“likes”。
如何修改我的查询,使其删除现有投票并替换为新投票??
这是我喜欢的模型:
'use strict';
module.exports = (sequelize, DataTypes) => {
const Like = sequelize.define('Like', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: DataTypes.INTEGER
},
userId: {
allowNull: false,
primaryKey: true,
type: DataTypes.INTEGER
},
thread_id: {
allowNull: false,
primaryKey: true,
type: DataTypes.INTEGER
},
createdAt: {
allowNull: false,
type: DataTypes.DATE
},
updatedAt: {
allowNull: false,
type: DataTypes.DATE
},
vote: {
type: DataTypes.INTEGER
}
}, {});
Like.associate = function(models) {
// associations can be defined here
};
return Like;
};
1条答案
按热度按时间o2gm4chl1#
在这里,您可以做的是,创建一个复合键,使用
注:
然后像这样创建:
注:
永远不要运行原始查询,就像您在代码示例中所做的那样,总是使用模型来执行crud,这样您就可以利用sequelizejs的所有特性