用户如何使用 sequelize postgres nodejs 互相喜欢发帖? [英] How can users like each others post using sequelize postgres nodejs?

查看:50
本文介绍了用户如何使用 sequelize postgres nodejs 互相喜欢发帖?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力实现用户可以喜欢彼此的帖子.

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

这是我的喜欢模型:

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,
  },

这是我的帖子模型:

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

这是我的用户模型:

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

这是我的联想:

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?

推荐答案

添加喜欢应该是一个 post 操作,以添加将用户链接到帖子的新关联.正如您所建议的那样,用户和帖子之间应该是一对一的,因为不可能多次喜欢一个帖子.

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.

取消喜欢就像删除关联一样简单,因此您可以通过对用户和喜欢中间表中的帖子之间的关联执行 get 来测试某个帖子是否被特定用户喜欢.如果它不存在,则用户不喜欢它(并且应该被允许喜欢它),反之亦然.

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.

这篇关于用户如何使用 sequelize postgres nodejs 互相喜欢发帖?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆