i'm implementing a like system for a project. And I need some help with a query.
Basically i have 2 buttons (upvote and downvote) that call my function and give the id of a thread, the username voting, and the vote ( 1 or -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]
})
}
But now in my Likes table althought thread_id and userId ara both primary keys, inserts multiple repeated "Likes".
How I can modify my query so it deletes an existing vote and replaces it for a new one??
Here is my Like model:
'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;
};