How can users like each others post using sequelize postgres nodejs?

寵の児 提交于 2020-12-13 03:14:18

问题


I am trying to implement that users can like each others post.

Here is my Likes model:

const Likes = db.define("Likes", {

id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER,
  },
  PostId: {
  type: Sequelize.INTEGER,
   references: {
  model: "Post",
  key: "id",
   },
onUpdate: "cascade",
onDelete: "cascade",
 },
 userId: {
type: Sequelize.INTEGER,
references: {
  model: "User",
  key: "id",
},
onUpdate: "cascade",
onDelete: "cascade",
 },
 createdAt: {
allowNull: false,
type: Sequelize.DATE,
 },
updatedAt: {
allowNull: false,
type: Sequelize.DATE,
  },

Here is my Post Model:

id: {
  type: Sequelize.INTEGER,
  primaryKey: true,
  autoIncrement: true,
},
title: {
  type: Sequelize.STRING,
},
userId: {
  type: Sequelize.INTEGER,
},

Here is my Users Model:

id: {
  type: Sequelize.INTEGER,
  primaryKey: true,
  autoIncrement: true,
},
name: {
  type: Sequelize.STRING,
},

and here are my associations:

db.Likes.belongsTo(db.User, { foreignKey: "userId", targetKey: "id" });
db.Likes.belongsTo(db.Post, { foreignKey: "PostId", targetKey: "id" });
db.Post.hasMany(db.Likes, { foreignKey: "PostId", targetKey: "id" });
db.User.hasMany(db.Likes, { foreignKey: "userId", targetKey: "id" });

how should i go about and implement the like and unlike action?

is it supposed to be a get request or a post request?


回答1:


Adding a like should be a post action to add a new association linking the user to the post. This should be one-to-one between user and post as you have suggested, since it should not be possible to like a post more than once.

Unliking is as simple as deleting the association, so you can test if a post is liked by a particular user by doing a get for an association between the user and the post in your likes intermediate table. If it doesn't exist, the user hasn't liked it (and should be allowed to like it) and vice-versa.



来源:https://stackoverflow.com/questions/64856571/how-can-users-like-each-others-post-using-sequelize-postgres-nodejs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!