You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Sequelize关联计数时空表返回1而非0的问题求助

解决Sequelize统计关联表空表时返回1而非0的问题

问题原因

你当前代码里用了COUNT('comments.id'),这里的'comments.id'是字符串常量,不是数据库字段的正确引用。PostgreSQL的COUNT()函数会统计所有非NULL的输入值,字符串常量永远是非NULL状态,所以哪怕关联的Comments表为空,统计结果也会是1。

解决方案

把COUNT('comments.id')替换成COUNT(Sequelize.col('comments.id')),用Sequelize.col()来正确指向关联表的字段。当没有关联评论时,comments.id会是NULL,COUNT(NULL)的结果就是0。

修改后的代码:

this.publicationModel.findAll({
  attributes: {
    include: [
      [Sequelize.cast(Sequelize.fn('COUNT', Sequelize.col('comments.id')), 'int'), 'commentsCount'],
    ]
  },
  include: ['user', {
    model: Comment,
    attributes: [],
    required: false, // 显式指定左连接,保证无关联数据时仍返回主表记录
  }],
  group: ["Publication.id", "user.id"],
  order: ["id"],
});

效果验证

修改后生成的SQL中,统计部分会变为:

CAST(COUNT("comments"."id") AS INT) AS "commentsCount"

此时执行SQL,当Comments表为空时,comments.id为NULL,COUNT()会返回0,符合预期。

内容的提问来源于stack exchange,提问作者Алексей Смирнов

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 23:28:18