简体   繁体   中英

Sequelize Join with Count of matching id

I have two models, Post and PostLikes, where PostLikes.postId references Post.id. I am trying to run Post.findAll({}) where PostLike.postId = Post.id. I have tried many, many things and have been unable to get anywhere. Here is what I tried last, which shows all of the info from Post, but LikeCount is 0.

await Post.findAll({
    attributes: [
      "id",
      "username",
      "title",
      "body",
      "createdAt",
      "updatedAt",
      [sequelize.fn("COUNT", sequelize.col("PostLikes.postId")), "LikeCount"]
    ],
    include: [
      {
        model: PostLike,
        attributes: []
      }
    ],
    group: ["Post.id"]
})

Edit: As requested, here are my model defs.

Post:

module.exports = (sequelize, DataTypes) => {
  const Post = sequelize.define(
    "Post",
    {
      title: DataTypes.STRING,
      body: DataTypes.TEXT,
      userId: DataTypes.INTEGER,
      username: DataTypes.STRING
    },
    {}
  );
  Post.associate = function(models) {
    Post.belongsTo(models.User, {
      foreignKey: "username",
      onDelete: "cascade"
    });
    Post.belongsTo(models.User, {
      foreignKey: "userId",
      onDelete: "cascade"
    });
    Post.hasMany(models.Comment, { foreignKey: "id" });
    Post.hasMany(models.PostLike, { foreignKey: "id" });
  };
  return Post;
};

PostLike:

module.exports = (sequelize, DataTypes) => {
  const PostLike = sequelize.define(
    "PostLike",
    {
      liked: DataTypes.BOOLEAN,
      userId: DataTypes.INTEGER,
      postId: DataTypes.INTEGER
    },
    {}
  );
  PostLike.associate = function(models) {
    PostLike.belongsTo(models.Post, {
      foreignKey: "postId",
      onDelete: "cascade"
    });
    PostLike.belongsTo(models.User, {
      foreignKey: "userId",
      onDelete: "cascade"
    });
  };
  return PostLike;
};

So there seems to be something wrong with this setup, i never setup my associations this way(sequelize is very confusing and the docs seem to be inconsistent with their examples), so it's hard to tell. But i've played with your models, and i was getting some constraint error, when i was trying to add more than one PostLike. I changed it a bit, and got it to work( i removed the user references, being that they are irrelevant for the problem here):

  module.exports = (sequelize, DataTypes) => {
        const Post = sequelize.define(
            "Post",
            {
                title: DataTypes.STRING,
                body: DataTypes.TEXT,
                userId: DataTypes.INTEGER,
                username: DataTypes.STRING
            },
            {}
        );
        Post.associate = function (models) {


            Post.hasMany(models.PostLike);
        };


        return Post;
    };



  module.exports = (sequelize, DataTypes) => {
    const PostLike = sequelize.define(
        "PostLike",
        {
          liked: DataTypes.BOOLEAN,
          userId: DataTypes.INTEGER,         
        },
        {}
      );
      PostLike.associate = function(models) {//
        PostLike.belongsTo(models.Post);        
      }; 

    return PostLike;
  };

After inserting one post, and two postLikes, this is the result: 在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM