gpt4 book ai didi

mysql - 在 sequelize 查询中避免重复

转载 作者:行者123 更新时间:2023-11-29 03:17:20 28 4
gpt4 key购买 nike

我正在为一个项目实现类似的系统。我需要一些查询帮助。

基本上我有 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 都是主键,但插入了多个重复的“Likes”。

我如何修改我的查询以删除现有投票并将其替换为新投票?

这是我的 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;
};

最佳答案

在这里,你可以做的是,创建一个复合键,用这个

userId: {
allowNull: false,
unique:"vote_user" // <------ HERE
type: DataTypes.INTEGER
},
thread_id: {
allowNull: false,
unique:"vote_user" // <------ HERE
type: DataTypes.INTEGER
},

NOTE :

 // 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

Note :

Never never run raw query , like you have did in your code sample , always use the model to perform CRUD , this way you can utilize all the features of sequelizejs

关于mysql - 在 sequelize 查询中避免重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53281798/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com