Sequelize associate 并查询这个 mysql 查询

Sequelize associate and query for this mysql query

我只想在 sequelize 中执行这个简单的 mysql 查询,但它真的很混乱..

SELECT *,
       (SELECT COUNT(*)
         FROM  user_review_like
        WHERE  user_review_like.review_id = review.id)
FROM  reviews

所以我这样试了。

const reviewList = await Review.findAndCountAll({
  attributes: ['*', fn('COUNT', col('user_review_like'))],
  include: [
    {
      model: UserReviewLike,
      attributes: [],
    },
  ],
  where,
  raw: true,
  offset: offset,
  limit: 5,
  order,
});

但是它说 'userReviewLike is not associated to Review!'

型号'review':

static associate(db) {
  db.Review.belongsTo(db.User); --> for matching review writer and users
  db.Review.belongsToMany(db.User, {through: 'user_review_like', foreignKey: 'review_id'});
}

型号'user':

static associate(db) {
  db.User.hasMany(db.Review);
  db.User.belongsToMany(db.Review, {through: 'user_review_like', foreignKey: 'user_id'});
}

型号'userReviewLike':

{
    user_id: {
    },
    review_id: {
    },
  },
static associate(db) {
db.UserReviewLike.belongsTo(db.User, {
  foreignKey: 'user_id'
});
db.UserReviewLike.belongsTo(db.Review, {
  foreignKey: 'review_id'
});

}

这似乎更方便,因为我正在设置位置和动态订购, 但我对连接查询感到困惑。

有什么建议吗

谢谢

为了能够在 include 中显式指示连接模型,您还应该显式定义从 ReviewUserReviewLike 的关联:

db.Review.hasMany(db.UserReviewLike, { foreignKey: 'review_id' })

而且我想可以使用 COUNT 作为子查询,你需要使用 Sequelize.literal,否则你会得到类似 SELECT *, COUNT(*) ...

的东西
const reviewList = await Review.findAndCountAll({
  attributes: { include: [
    [literal('(SELECT COUNT(*)
         FROM  user_review_like
        WHERE  user_review_like.review_id = review.id)'), 'like_count']
  ]
  },
  where,
  raw: true,
  offset: offset,
  limit: 5,
  order,
});