我正在为项目实施类似的系统。我需要查询方面的帮助。
基本上,我有2个按钮(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_id和userId都是两个主键,但会插入多个重复的“赞”。
我如何修改查询,以便删除现有的投票并将其替换为新的投票?
这是我的Like模型:
'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;
};
答案 0 :(得分:0)
在这里,您可以做的是,使用此
创建一个复合键。userId: {
allowNull: false,
unique:"vote_user" // <------ HERE
type: DataTypes.INTEGER
},
thread_id: {
allowNull: false,
unique:"vote_user" // <------ HERE
type: DataTypes.INTEGER
},
// Creating two objects with the same value will throw an error. The unique property can be either a // boolean, or a string. If you provide the same string for multiple columns, they will form a // composite unique key. uniqueOne: { type: Sequelize.STRING, unique: 'compositeIndex' }, uniqueTwo: { type: Sequelize.INTEGER, unique: 'compositeIndex' },
然后像这样创建它:
Like.create({ userId : 1 , thread_id : 1 }).then(data => {
// success
}).catch(err => {
// error if same data exists
})
// <--- this will check that if there any entry with userId 1 and thread_id 1 ,
// if yes , then this will throw error
// if no then will create an entry for that
注意:
永远不要运行原始查询,就像您在代码示例中所做的那样,请始终使用模型执行CRUD,这样您就可以利用所有 sequelizejs的功能