我刚开始使用sequelize并尝试重现以下查询。
我有以下模型结构:Review
,Entity
,ReviewThank
每个Entity
可以包含多个Reviews
,每个Review
可以包含多个ReviewThanks
。
每个评论的属性都是&{39; thumbUp
' (boolean
)评级。
我尝试生成以下查询以获得' thankCount
'对于每个审核,以及每个thumbUpCount
的实体评分 - totalCount
和Review
:
SELECT * FROM (
SELECT COUNT("Review"."id") AS "totalCount", "Review"."EntityId", COUNT(CASE WHEN "Review"."thumbUp" THEN 1 END) AS "thumbUpCount"
FROM "Reviews" AS "Review" GROUP BY "Review"."EntityId"
) AS "EntityRatingTable" LEFT JOIN (
SELECT "Review"."id", "Review"."EntityId", "Review"."uid", "Review"."thumbUp", "Review"."caption", COUNT("ReviewThanks"."id") AS "thankCount"
FROM "Reviews" AS "Review" LEFT OUTER JOIN "ReviewThanks" AS "ReviewThanks" ON "Review"."id" = "ReviewThanks"."ReviewId"
WHERE "Review"."UserId" IN (1) GROUP BY "Review"."id"
) AS "ReviewsTable" ON "ReviewsTable"."EntityId" = "EntityRatingTable"."EntityId";
是否有可能在续集中产生这个?我已经得到了" ReviewsTable
"查询工作正常,但不确定如何(或如果可能)我可以加入" EntityRatingTable
"?
这是我到目前为止所得到的:
models.Review.findAll({
attributes: {
include: [
[models.sequelize.fn('COUNT', models.sequelize.col('ReviewThanks.id')), 'thankCount'],
[models.sequelize.fn('COUNT', models.sequelize.col('Review.id')), 'reviewCount'],
],
exclude: ["EntityId", "UserId"],
},
include: [
{
model: models.ReviewThank,
attributes: [],
}, {
model: models.Entity,
}
],
group: ['"Review"."id"', '"Entity.id"'],
})