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
相关产品推荐
相关产品推荐

