问题
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