Sequelize查询中如何隐藏关联的嵌套模型返回结果
解决Sequelize查询中过滤关联模型但不返回关联对象的问题
你的问题出在错误使用了attributes: { include: [] }——这个配置的意思是"保留模型默认字段,额外包含空数组里的字段",所以仍会返回Employee和Manager的主键,最终导致嵌套对象出现在结果中。要彻底移除这些嵌套对象,需要调整两个关键点:
正确的配置方案
直接给关联模型设置attributes: [](空数组),明确指定不返回该模型的任何字段;同时在顶层只声明需要返回的Document字段:
findOptions = { attributes: ['documentId'], // 仅返回文档ID include: { model: Employee, required: true, as: 'employee', attributes: [], // 不返回Employee的任何字段 include: { model: Manager, as: 'manager', attributes: [], // 不返回Manager的任何字段 where: { managerId: { [Op.in]: authorized.managerIds } } } } };
原理说明
当关联模型的attributes设为空数组时,Sequelize不会为该模型生成任何字段的查询语句,也不会在最终结果中保留对应的嵌套对象。配合顶层的attributes: ['documentId'],就能确保返回结果只包含你需要的文档ID。
备选方案:用子查询过滤(避免include关联)
如果不想通过include关联来过滤,也可以用子查询直接定位符合条件的员工ID,再查询对应的文档:
findOptions = { attributes: ['documentId'], where: { employeeId: { [Op.in]: sequelize.literal(`(SELECT employeeId FROM Employees WHERE managerId IN (${authorized.managerIds.join(',')}))`) } } };
这种方式完全不涉及关联模型的嵌套,结果自然不会出现多余的对象。
内容的提问来源于stack exchange,提问作者Jozef
相关产品推荐
相关产品推荐

