繁体   English   中英

在多对多关系中计数

[英]Count in Many-to-Many relationship

我想在获取帖子详细信息时计算喜欢的数量。

User Model

User.init(
    {
      id: {
        allowNull: false,
        primaryKey: true,
        type: DataTypes.UUID,
        defaultValue: DataTypes.UUIDV4,
      },
      userName: {
        type: DataTypes.STRING,
        allowNull: false,
        unique: true,
        field: 'user_name',
      },
    }
  );
static associate(models) {
      // User has many posts --> One-to-Many Relationship
      this.hasMany(models.Post, {
        foreignKey: 'userId',
      });

      // Likes relationship
      this.belongsToMany(models.Post, {
        through: 'PostLikes',
        foreignKey: 'userId',
        as: 'likes',
      });
    }

这是Post Model

Post.init(
    {
      id: {
        type: DataTypes.UUID,
        primaryKey: true,
        allowNull: false,
        defaultValue: DataTypes.UUIDV4,
      },
      body: {
        type: DataTypes.STRING,
        allowNull: false,
      },
    }
  );
static associate(models) {
      // User-Post Relationship
      this.belongsTo(models.User, {
        foreignKey: 'userId',
      });

      // Likes Relationship
      this.belongsToMany(models.User, {
        through: 'PostLikes',
        foreignKey: 'postId',
        as: 'likes',
      });
    }

因此,它现在创建了一个联接表PostLikes ,我正在尝试获取该帖子以及该帖子的点赞数和点赞数的查询。

const postsIdCol = '"likes->PostLikes"."postId"';
const usersIdCol = '"likes->PostLikes"."userId"';
const postCol = '"Post"."id"';

const response = await Post.findOne({
      where: {
        id: postid,
      },
      // includeIgnoreAttributes : false,
      attributes: [
        'id', 'body', 'createdAt', 
        [sequelize.literal(`COUNT(${postsIdCol}) OVER (PARTITION BY ${postCol})`), 'likesCount'],
      ],
      include: [
        {                               
          model: Comment,          ----> Post is also associated with comments, ignore this
          as: 'comments',
          attributes: ['id', 'content', 'createdAt', 'updatedAt'],
        },
        {
          model: User,
          as: 'likes',
          through: {
            attributes: [],
          },
          attributes: ['id', 'userName'],
        },
      ],
    });

    return response;

我在执行此查询时得到的响应是这样的:

{
    "data": {
        "id": "182d6377-5bf6-4b65-9e29-cb79acc85c0a",
        "body": "hoping for the best",
        "likesCount": "6",                -----> this should be 3
        "likes": [
            {
                "id": "1af4b9ea-7c58-486f-a37a-e46461487b06",
                "userName": "sdfbsd",
            },
            {
                "id": "484202b0-a6d9-416d-a8e2-6681deffa3d1",
                "userName": "ndnadonfsu",
            },
            {
                "id": "b3c70bee-e839-4449-b213-62813af031d1",
                "userName": "difniandca",
            }
        ]
    }
}

您需要另一个关联中的另一个 PARTITION BY 列,而不是您要计算的那个。

例如,如果要统计点赞数,则需要按父 ID(Post.id)和其他关联 ID(Comment.id)进行分区。

如果要统计评论,则需要按父 id (Post.id) 和其他关联 id ("likes->PostLikes"."UserId") 进行分区。

[Sequelize.literal(`COUNT(${postsIdCol}) OVER (PARTITION BY ${postCol}, "Comments"."id")`), 'likesCount']

在它说“评论”的地方,您需要添加您的评论表名称。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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