避免sequelize查询中的重复

atmip9wb  于 2021-06-18  发布在  Mysql
关注(0)|答案(1)|浏览(347)

我正在为一个项目实施一个类似的系统。我需要一些帮助。
基本上我有两个按钮(upvote和downvote),它们调用我的函数并给出线程的id、用户名投票和投票(1或-1)。

  1. addPositiveorNegativeLikes = function(thread_id, username, vote) {
  2. sequelize.query('INSERT INTO Likes (thread_id, userId, vote, createdAt, updatedAt)
  3. VALUES((?), (SELECT id FROM Users WHERE username=(?)), (?), (?), (?))
  4. ON DUPLICATE KEY UPDATE thread_id=(?), userId=(SELECT id FROM Users WHERE username=(?))',{
  5. replacements: [thread_id, username, vote, new Date(), new Date(), thread_id, username]
  6. })
  7. }

但现在在我的likes表中,虽然thread\u id和userid都是主键,但插入了多个重复的“likes”。
如何修改我的查询,使其删除现有投票并替换为新投票??
这是我喜欢的模型:

  1. 'use strict';
  2. module.exports = (sequelize, DataTypes) => {
  3. const Like = sequelize.define('Like', {
  4. id: {
  5. allowNull: false,
  6. autoIncrement: true,
  7. primaryKey: true,
  8. type: DataTypes.INTEGER
  9. },
  10. userId: {
  11. allowNull: false,
  12. primaryKey: true,
  13. type: DataTypes.INTEGER
  14. },
  15. thread_id: {
  16. allowNull: false,
  17. primaryKey: true,
  18. type: DataTypes.INTEGER
  19. },
  20. createdAt: {
  21. allowNull: false,
  22. type: DataTypes.DATE
  23. },
  24. updatedAt: {
  25. allowNull: false,
  26. type: DataTypes.DATE
  27. },
  28. vote: {
  29. type: DataTypes.INTEGER
  30. }
  31. }, {});
  32. Like.associate = function(models) {
  33. // associations can be defined here
  34. };
  35. return Like;
  36. };
o2gm4chl

o2gm4chl1#

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

  1. userId: {
  2. allowNull: false,
  3. unique:"vote_user" // <------ HERE
  4. type: DataTypes.INTEGER
  5. },
  6. thread_id: {
  7. allowNull: false,
  8. unique:"vote_user" // <------ HERE
  9. type: DataTypes.INTEGER
  10. },

注:

  1. // Creating two objects with the same value will throw an error. The unique property can be either a
  2. // boolean, or a string. If you provide the same string for multiple columns, they will form a
  3. // composite unique key.
  4. uniqueOne: { type: Sequelize.STRING, unique: 'compositeIndex' },
  5. uniqueTwo: { type: Sequelize.INTEGER, unique: 'compositeIndex' },

然后像这样创建:

  1. Like.create({ userId : 1 , thread_id : 1 }).then(data => {
  2. // success
  3. }).catch(err => {
  4. // error if same data exists
  5. })
  6. // <--- this will check that if there any entry with userId 1 and thread_id 1 ,
  7. // if yes , then this will throw error
  8. // if no then will create an entry for that

注:
永远不要运行原始查询,就像您在代码示例中所做的那样,总是使用模型来执行crud,这样您就可以利用sequelizejs的所有特性

展开查看全部

相关问题