Has the user liked the post before or not using Sequelize

混江龙づ霸主 提交于 2020-11-29 23:11:51

问题


Currently when a user likes a post, that like record gets added to my Likes table with the userId and the postId.

Now, when a user is looking at a post, I want to determine if they liked the post before or not. I understand that to do so, I need to determine this in my get request when i am calling for the post information.

When i am calling for post information, I need to check the Likes table for a record of the userId of the current user AND the postId for the current post. If this exists then i need to return a parameter called isLiked and set it to true, if it does not exist then isLiked=false.

Here is my Post model:

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

Here is my Likes Model:

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

Here is my User Model:

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

Here are my associations:

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" });

Update

I kept researching and found since i am using a JWT middleware to sign my user token, and i am currently checking to see if the current user has any records in the likes table, i tried the following but can someone tell me if this approach is correct?

 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 );

 });

回答1:


You don't need to request Like once again, you got all post's likes at your hand:

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;
 ...



回答2:


You don't need to specify all the fields unless you want to override something, otherwise Sequelize can generate most of the columns for you.

const User = sequelize.define(
  'user',
  {
    name: {
      type: Sequelize.STRING,
    },
  },
  { /* options */ }
);

const Post = sequelize.define(
  'post',
  {
    title: {
      type: Sequelize.STRING,
    },
  },
  { /* options */ }
);

// the join table so you can reference it, but doesn't need any columns including primary key (unless you want to a "super join")
const Likes = sequelize.define(
  'likes',
  {}, // no columns here
  { /* options */ }
);

Creating the associations between the models will create most of the foreignKey fields automatically. Use the through keyword on the Likes relationships to make it many-to-many.


// Users can have many Posts
User.hasMany(Post);

// Posts belong to one User
Post.belongsTo(User);

// Users can like more than one Post through the `likes` join table
User.hasMany(Post, { as: 'likes', through: 'likes' });

// Posts can be liked by more than one User through the `likes` join table
Post.hasMany(User, { as: 'likes', through: 'likes' });

You don't need to store the number of likes because you can summarize it through the join table.

// Get the 'likes' count for a Post, instead of saving it on the post
const posts = await Post.findAll({
  attributes: {
    include: [
      [sequelize.fn('COUNT', sequelize.col('likes.userId')), 'likesCount'],
    ],
  },
  include: [
    {
      model: User,
      as: 'likes',
      though: 'likes',
      attributes: [],
      required: false,
    },
  ],
});

// `posts` will be an array of Post instances that have a likesCount property
posts.forEach((post) => {
  console.log(`The post ${post.title} has ${post.likesCount} likes.`);
});

For an individual (or more than one) Post you can get the list of users who liked it via the post (or use the Like model and it's relationships).


// Get the user 'likes' for a Post
const post = await Post.findByPk(postId, {
  include: [
    {
      model: User,
      as: 'likes',
      though: 'likes',
      required: false,
    },
  ],
});

post.likes.forEach((like) => {
  console.log(`The user ${like.name} has liked the post ${post.title}.`);
});



来源:https://stackoverflow.com/questions/64906432/has-the-user-liked-the-post-before-or-not-using-sequelize

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!