如何在Sequelize中排除关联查询里的UserRole中间模型?
问题
我有User和Role两个模型,二者是多对多关联,因此创建了中间模型UserRole。但执行以下查询代码时,返回结果自动包含了UserRole模型的信息:
async getUser(conditionals: object) { return await this.userRepository.findOne({ where: { ...conditionals }, include: [{ model: Role, attributes: 'value' } ] }); }
当前返回结果(数据经jwt编解码,格式无需关注):
{ "userId": "7a145aea-72c8-4b96-a25b-b404f9b1bf5a", "username": "bl4drnnr", "roles": [ { "value": "USER", "UserRole": { "id": "e9d2afe8-ddd1-4311-ab14-6638b79d0d80", "userId": "7a145aea-72c8-4b96-a25b-b404f9b1bf5a", "roleId": "123e4567-e89b-12d3-a456-426614174001" } } ], "type": "access", "iat": 1659878703, "exp": 1659879603 }
我希望排除UserRole模型,得到如下结果:
{ "userId": "7a145aea-72c8-4b96-a25b-b404f9b1bf5a", "username": "bl4drnnr", "roles": [ { "value": "USER" } ], "type": "access", "iat": 1659878703, "exp": 1659879603 }
我试过用Sequelize的exclude属性,但它只对字段生效,无法排除模型。请问怎么在数据库查询中排除UserRole模型?
解决方案
有两种方式可以解决这个问题:
1. 单次查询时显式排除中间表数据
在include的配置里添加through: { attributes: [] },告诉Sequelize不要返回中间表UserRole的任何数据:
async getUser(conditionals: object) { return await this.userRepository.findOne({ where: { ...conditionals }, include: [{ model: Role, attributes: ['value'], through: { attributes: [] } // 关键配置,排除中间表数据 } ] }); }
2. 模型关联定义时默认排除中间表数据
如果希望所有关联查询都不返回中间表数据,可以在定义User和Role的多对多关联时,设置through的attributes为空数组:
// User模型关联Role时的配置 User.belongsToMany(Role, { through: { model: UserRole, attributes: [] // 默认不返回中间表字段 }, foreignKey: 'userId', otherKey: 'roleId' }); // Role模型关联User时的配置 Role.belongsToMany(User, { through: { model: UserRole, attributes: [] }, foreignKey: 'roleId', otherKey: 'userId' });
配置完成后,所有查询包含Role或User的关联数据时,都不会自动带出UserRole的内容,无需每次查询单独配置。
内容的提问来源于stack exchange,提问作者dokichan
相关产品推荐
相关产品推荐

