【发布时间】:2021-03-02 12:13:31
【问题描述】:
当前,当用户喜欢某个帖子时,该喜欢的记录会使用 userId 和 postId 添加到我的 Likes 表中。
现在,当用户查看帖子时,我想确定他们之前是否喜欢该帖子。我知道要这样做,我需要在我调用发布信息时在我的 get 请求中确定这一点。
当我调用帖子信息时,我需要检查 Likes 表以获取当前用户的 userId 和当前帖子的 postId 的记录。如果存在,那么我需要返回一个名为 isLiked 的参数并将其设置为 true,如果它不存在则 isLiked=false。
这是我的帖子模型:
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true,
},
title: {
type: Sequelize.STRING,
},
userId: {
type: Sequelize.INTEGER,
},
likesCount:{
type:Sequelize.INTEGER,
defaultValue:0,
validate: {
min: 0,
}
},
这是我的点赞模型:
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER,
},
PostId: {
type: Sequelize.INTEGER,
references: {
model: "Post",
key: "id",
},
},
userId: {
type: Sequelize.INTEGER,
references: {
model: "User",
key: "id",
},
},
这是我的用户模型:
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true,
},
name: {
type: Sequelize.STRING,
},
这是我的联想:
User.hasMany(Post, { foreignKey: "userId" });
Post.belongsTo(User, { foreignKey: "userId" });
Post.hasMany(Likes, { foreignKey: "PostId", targetKey: "id" });
Likes.belongsTo(Post, { foreignKey: "PostId", targetKey: "id" });
User.hasMany(Likes, { foreignKey: "userId", targetKey: "id" });
Likes.belongsTo(User, { foreignKey: "userId", targetKey: "id" });
更新
我一直在研究并发现,因为我正在使用 JWT 中间件来签署我的用户令牌,并且我目前正在检查当前用户是否在 likes 表中有任何记录,我尝试了以下但有人可以告诉我是否这种做法正确吗?
router.get("/", async (req, res) => {
const posts = await Post.findAll({
order: [["createdAt", "DESC"]],
include: [
{ model: Post_Image, attributes: ["id", "images"] },
{ model: Likes, attributes: ["id", "PostId", "userId"] },
],
});
if (!posts) return res.status(404).send();
const baseUrl = config.get("assetsBaseUrl");
const plainPosts = posts.map((x) => x.get({ plain: true }));
const resultPosts = [];
for (const post of plainPosts) {
let isLiked = false;
let like = await Likes.findOne({
where: {
[Op.and]: [{ PostId: post.id) }, { userId:
req.user.id }],
},
});
if (like) isLiked = true;
const { Post_Images, ...postAttributes } = post;
const IMAGES = Post_Images.map((postImage) => ({
url: `${baseUrl}${postImage.images}_full.jpg`,
thumbnailUrl: `${baseUrl}${postImage.images}_thumb.jpg`,
}));
resultPosts.push({ ...postAttributes, images: IMAGES, isLiked
});
}
res.send( resultPosts );
});
【问题讨论】:
-
显示整个路线以及如何发送请求以获取 isLiked
-
嗨@Anatoly,我正在尝试在我的get all posts请求中创建一个查询,检查likes表中的userId记录和postId如果这个记录存在,那么我将返回一个名为is的参数喜欢并将其设置为 true,如果不存在 isLiked=false。我尝试在我的 for(const post of plainPosts){} 循环中实现这一点。我用一个例子更新了我的问题。谢谢
-
我认为您需要简化它。有很多问题和困惑。直接说出你需要什么和你做了什么。删除不需要变得更好的信息。我会尝试为您编辑您的帖子。
标签: node.js sequelize.js