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

Sequelize关联查询如何仅返回指定列,排除结果中多余的ID字段

问题原因

你返回结果里多余的UserId和RoleId字段来自多对多关联的中间表aspnet_UsersInRoles,Sequelize在做多对多关联查询时,默认会将中间表的关联字段一同返回,即使你已经指定了主表和关联表的返回字段。

解决方案

只需要在include配置中添加through参数,指定中间表不返回任何字段即可,修改后的查询代码如下:

test.aspnet_Users.findAll({
    logging: console.log,
    where: { LoweredUserName: `mcad2\\${user}` },
    attributes: ['LoweredUserName'],
    include: {
        model: test.aspnet_Roles,
        as: 'RoleId_aspnet_Roles',
        attributes: ['LoweredRoleName'],
        // 新增配置:指定中间表不返回任何字段
        through: {
            attributes: []
        }
    }
}).then(user => {
    console.log('\n\n' + JSON.stringify(user))
})

如果后续需要返回中间表的特定字段,只需要将字段名填入through.attributes的数组中即可。

内容的提问来源于stack exchange,提问作者Geoff

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 11:18:02