使用sql / sequelize通过userId获取喜欢的帖子并获取帖子的喜欢次数

时间:2020-06-15 13:06:57

标签: sql node.js sequelize.js

您能否帮助我进行此查询。我需要使用“ userId”查询用户喜欢的所有帖子。另外,我需要对包含在属性中的帖子添加“ like_count”。

Table "public.posts"
  Column   |           Type           | Collation | Nullable |      Default      
-----------+--------------------------+-----------+----------+-------------------
 id        | uuid                     |           | not null | gen_random_uuid()
 body      | text                     |           | not null | 
 imageId   | uuid                     |           |          | 
 userId    | uuid                     |           |          | 
 deletedAt | timestamp with time zone |           |          | 
Table "public.postReactions"
  Column   |           Type           | Collation | Nullable |      Default      
-----------+--------------------------+-----------+----------+-------------------
 id        | uuid                     |           | not null | gen_random_uuid()
 isLike    | boolean                  |           | not null | true
 userId    | uuid                     |           |          | 
 postId    | uuid                     |           |          | 

我已经完成了第一部分任务。我得到了所有用户喜欢的帖子,但是在示例中,我只包含了放置当前用户的likes(postReactions)!所以like_count是错误的(

async getPosts(filter) {
    const {
      from: offset,
      count: limit,
      likedByUser
    } = filter;

    let where = {};

    if (likedByUser) {
      where = sequelize.where(sequelize.literal(`CASE WHEN "postReactions"."isLike" = true AND "postReactions"."userId"::text = '${likedByUser}' THEN 1 ELSE 0 END`), 1)
    }

    return this.model.findAll({
      where,
      attributes: {
        include: [
          [sequelize.fn('SUM', sequelize.literal(likeCase(true))), 'likeCount'],
          [sequelize.fn('SUM', sequelize.literal(likeCase(false))), 'dislikeCount'],
        ]
      },
      include: [{
        model: PostReactionModel,
        attributes: ['id'],
        duplicating: false,
      }],
      group: [
        'post.id',
        'postReactions.id',
      ],
      order: [['createdAt', 'DESC']],
      offset,
      limit
    });
  }

更改此部分也有类似结果。

include: [{
        model: PostReactionModel,
        attributes: ['id'],
        **where: { userId }**
        duplicating: false,
      }],

查询结果为:

dislikeCount: "0"
id: "5c0d59ca-03e9-4aa4-829b-3642f80b721d"
likeCount: "1"
postReactions: Array(1)
0: {id: "db22c285-bef1-4abd-aad0-31bcd091ddf8"}
length: 1

看到我在这篇文章上只有我的postReaction,但是还有很多其他的反应!

1 个答案:

答案 0 :(得分:0)

Hıı,我有类似的架构。我正在分享我的查询,也许对您有益

productDetail: async function (req, res, next) {
    const productId = parseInt(req.params.productId);

    const getEvaluationCountQuery = function (value) {
        return `COUNT(case "evaluationGroup->evaluationAttributes->evaluations"."evaluation" when ${value} then 1 else null end)`
    }

    const product = await database.models.Product.findOne({
        where: {id: productId},
        include: [
            {
                model: database.models.EvaluationGroup,
                as: 'evaluationGroup',
                include: {
                    model: database.models.EvaluationAttribute,
                    as: 'evaluationAttributes',
                    attributes: {
                        include: [
                            [
                                database.literal(getEvaluationCountQuery(1)),
                                'upVote'
                            ],
                            [
                                database.literal(getEvaluationCountQuery(0)),
                                'downVote'
                            ],
                        ]
                    },
                    through: {
                        attributes: []
                    },
                    include: {
                        model: database.models.Evaluation,
                        as: 'evaluations',
                        where: {productId: productId},
                        attributes: [],
                        required: false,
                    },
                }
            },
        ],
        group: [
            'Product.id',
            'category.id',
            'evaluationGroup.id',
            'evaluationGroup->evaluationAttributes.id'
        ],
    });

    if (product) {
        response.ok(res, product);
    } else {
        response.error(res);
    }
},
相关问题