Sequelize关联查询include操作如何排除关联表主键列避免GROUP BY报错
问题原因
该报错是因为Sequelize默认会自动将关联模型的主键(此处为otherModel.id)追加到SELECT查询列表中,哪怕你显式指定了include的attributes仅取userId。而MySQL开启ONLY_FULL_GROUP_BY默认模式时,SELECT中所有非聚合字段都必须出现在GROUP BY子句中,未被分组的otherModel.id就触发了报错。
解决方案
- 方案1:在include的attributes配置中显式排除id字段
把include中的attributes从数组改为对象格式,通过exclude移除不需要的主键,同时保留需要的userId字段,示例代码如下:
model.findAll({ attributes: [ [Sequelize.fn('sum', Sequelize.col('price')), 'totalPrice'], ], include: { model: otherModel, attributes: { include: ['userId'], exclude: ['id'] // 显式排除主键,阻止Sequelize自动生成该字段的查询逻辑 }, where: { userId: 1 } }, group: ['otherModel.userId'] });
- 方案2:查询配置中添加
raw: true
如果你不需要Sequelize封装返回的关联模型实例,只需要原生查询结果,可以在findAll的顶层参数新增raw: true配置,此时Sequelize不会自动追加关联模型的主键字段:
model.findAll({ raw: true, attributes: [ [Sequelize.fn('sum', Sequelize.col('price')), 'totalPrice'], ], include: { model: otherModel, attributes: ['userId'], where: { userId: 1 } }, group: ['otherModel.userId'] });
- 方案3:高版本Sequelize专属配置
如果你使用的是Sequelize v6及以上版本,还可以在查询的顶层配置中添加includeIgnoreAttributes: false,也能避免自动追加关联模型的主键字段到SELECT列表中。
内容的提问来源于stack exchange,提问作者Jason M
相关产品推荐
相关产品推荐

