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

Sequelize findAll查询关联表指定属性结果冗余,如何优化输出?

解决Sequelize findAll返回冗余字段的问题

你可以通过调整attributes和include的配置直接得到期望结果,无需使用.map过滤:

方法1:通过关联字段别名指定返回字段

修改查询配置,在主模型的attributes中直接引用关联表字段并设置别名,同时将关联模型的attributes设为空数组,避免返回冗余的role.slug字段:

const { Op } = require('sequelize');

const user_role = await db.user_role.findAll({
    include: {
        model: db.role,
        as: 'role',
        attributes: [], // 不返回关联模型的原始字段
    },
    where: {
        userId: {
            [Op.eq]: userId
        }
    },
    attributes: [
        [db.Sequelize.col('role.slug'), 'slug'] // 从关联表取slug并设置别名
    ],
    raw: true
});

方法2:移除主模型attributes配置,配合nest: true(可选)

如果希望保留关联结构但只取指定字段,可开启nest: true,不过这种方式返回嵌套结构,需根据需求调整:

const user_role = await db.user_role.findAll({
    include: {
        model: db.role,
        as: 'role',
        attributes: ['slug'],
    },
    where: {
        userId: {
            [Op.eq]: userId
        }
    },
    attributes: [], // 不返回主模型的任何字段
    raw: true,
    nest: true
});

该方式返回结果为[{ role: { slug: 'admin' } }, ...],若要扁平结构,优先推荐第一种方法。

问题原因说明

你之前的代码中,主模型user_role的attributes配置了关联字段(未正确使用Sequelize.col指定),同时关联模型role也返回了slug字段,加上raw: true的默认行为会将关联字段以关联名.字段名格式拼接返回,因此出现了重复的slug和role.slug字段。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 13:55:07