我将如何检查当前用户是否喜欢该帖子。理想情况下,这类似于在instagram上发帖。心中充满红色,表示您喜欢它。
我将如何为后端添加类似的功能。
我知道后端会有一个布尔值,指示用户喜欢自己的帖子。在给定模型的情况下,我正在使用sequelize来使此功能正常工作。
理想情况下,帖子中的“喜欢”列应表明我是否喜欢该帖子。
req.session.user.id
获取当前用户。
post.controller
getPosts: async (req: Request, res: Response) => {
await models.Post.findAll({
include: [
{ model: models.User, as: "author", attributes: ["username"] },
{ model: models.Likes }
],
order: [["createdAt", "DESC"]],
limit: 6
}).then(posts => {
res.json(posts);
});
},
发布(模型)
"use strict";
module.exports = (sequelize, DataTypes) => {
var Post = sequelize.define("Post", {
title: DataTypes.STRING,
postContent: DataTypes.STRING,
liked: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false
},
likeCounts: {
type: DataTypes.INTEGER,
allowNull: false,
defaultValue: 0
},
authorId: DataTypes.INTEGER
}, {});
Post.associate = function (models) {
Post.belongsTo(models.User, {
as: "author",
foreignKey: "authorId",
onDelete: "CASCADE"
});
Post.hasMany(models.Likes, {
foreignKey: "resourceId",
timestamps: false,
targetKey: "id",
onDelete: "CASCADE"
});
};
Post.prototype.likedByMe = postId => { };
return Post;
};
//# sourceMappingURL=post.js.map
喜欢(模型)
"use strict";
module.exports = (sequelize, DataTypes) => {
var Likes = sequelize.define("Likes", {
userId: DataTypes.INTEGER,
resourceId: DataTypes.INTEGER,
likeByMe: {
type: DataTypes.BOOLEAN,
defaultValue: false,
allowNull: false
}
});
Likes.associate = function (models) {
// associations can be defined here
Likes.belongsTo(models.User, {
foreignKey: "userId",
timestamps: false,
onDelete: "CASCADE"
});
Likes.belongsTo(models.Post, {
foreignKey: "resourceId",
timestamps: false,
onDelete: "CASCADE",
targetKey: "id"
});
};
return Likes;
};
//# sourceMappingURL=likes.js.map
答案 0 :(得分:0)
类似
const iLikeIt = Like.findOne({ where: {
resourceId: postId,
userId: req.session.user.id,
}})
if (iLikeIt) {
// i liked it
} else {
// i didn't like it
}