gpt4 book ai didi

node.js - 用户之前是否喜欢该帖子或未使用 Sequelize

转载 作者:行者123 更新时间:2023-12-03 22:24:59 24 4
gpt4 key购买 nike

目前,当用户喜欢某个帖子时,该喜欢的记录会添加到我的 Likes 表中,其中包含 userId 和 postId。
现在,当用户查看帖子时,我想确定他们之前是否喜欢该帖子。我知道要这样做,我需要在我的 get 请求中在我要求发布信息时确定这一点。
当我调用帖子信息时,我需要检查 Likes 表以获取当前用户的 userId 和当前帖子的 postId 的记录。如果它存在,那么我需要返回一个名为 isLiked 的参数并将其设置为 true,如果它不存在则 isLiked=false。
这是我的 Post 模型:

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 中间件来签署我的用户 token ,并且我目前正在检查当前用户是否在喜欢表中有任何记录,我尝试了以下但有人可以告诉我这种方法是否适用正确的?
 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 );

});

最佳答案

你不需要再次请求 Like,你手​​头上有所有帖子的赞:

for (const post of plainPosts) {
// check if we have any like among posts' likes that is made by a certain user
const isLiked = post.Likes.some(x => x.userId === req.user.id);
const { Post_Images, ...postAttributes } = post;
...

关于node.js - 用户之前是否喜欢该帖子或未使用 Sequelize,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64906432/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com