Javascript 续集计数关联记录
我有一个帖子和一个评论模型,它们是关联的。一篇文章有很多评论,一篇评论属于一篇文章 后模型Javascript 续集计数关联记录,javascript,node.js,sequelize.js,Javascript,Node.js,Sequelize.js,我有一个帖子和一个评论模型,它们是关联的。一篇文章有很多评论,一篇评论属于一篇文章 后模型 class Post extends Model { static init(sequelize) { super.init( { description: { type: DataTypes.STRING, allowNull: false, validate: { notEmpt
class Post extends Model {
static init(sequelize) {
super.init(
{
description: {
type: DataTypes.STRING,
allowNull: false,
validate: {
notEmpty: {
args: true,
msg: "A description is required",
},
},
},
createdAt: {
type: DataTypes.DATE,
allowNull: false,
field: "created_at",
},
updatedAt: {
type: DataTypes.DATE,
allowNull: false,
field: "updated_at",
},
},
{ sequelize }
);
return this;
}
static associate(models) {
this.belongsTo(models.User, { foreignKey: "userId" });
this.hasMany(models.PostPhoto, { foreignKey: "postId" });
this.hasMany(models.Comment, { foreignKey: "postId" });
this.hasMany(models.Like, { foreignKey: "postId" });
}
}
注释模型
class Comment extends Model {
static init(sequelize) {
super.init(
{
comment: {
type: DataTypes.STRING,
allowNull: false,
validate: {
notEmpty: {
args: true,
msg: "A comment is required",
},
},
},
createdAt: {
type: DataTypes.DATE,
allowNull: false,
field: "created_at",
},
updatedAt: {
type: DataTypes.DATE,
allowNull: false,
field: "updated_at",
},
},
{ sequelize }
);
return this;
}
static associate(models) {
this.belongsTo(models.Post, { foreignKey: "postId" });
this.belongsTo(models.User, { foreignKey: "userId" });
}
}
我试图查找所有帖子,并统计每篇帖子中的评论数。我尝试了下面显示的查询,但它只检索一条记录,并且计数加倍
const posts = await Post.findAll({
order: [["createdAt", "DESC"]],
attributes: {
exclude: ["updatedAt"],
include: [
[Sequelize.fn("COUNT", Sequelize.col("comment")), "commentCount"],
],
},
include: [
{
model: Like,
},
{
model: Comment,
attributes: [],
},
],
});