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

Sequelize多对多关联查询如何按分类分组返回关联表单数据

解决方案

你需要分两步调整即可拿到预期的返回结构:

第一步:修正模型关联配置

Sequelize 提供了 belongsToMany 专门用于多对多关系关联,无需手动嵌套查询中间表。

调整 categories 模型关联

将原有 hasMany 关联替换为多对多关联:

Category.associate = function (models) {
    Category.belongsToMany(models.medforms, {
        through: models.medform_categories, // 指定中间表
        foreignKey: 'category_id', // 当前模型在中间表的外键
        otherKey: 'med_id', // 关联模型在中间表的外键
        as: 'medforms' // 关联结果别名,对应你要返回的medforms字段
    });
};

调整 medforms 模型关联(可选,后续反向查分类会用到)

MedForm.associate = function (models) {
    MedForm.belongsToMany(models.categories, {
        through: models.medform_categories,
        foreignKey: 'med_id',
        otherKey: 'category_id',
        as: 'categories'
    });
};

中间表 medform_categories 的关联逻辑无需修改。

第二步:修改控制器查询代码

无需嵌套查询中间表,直接关联 medforms 即可:

const db = require("../models");
const Categories = db.categories;
// 查全部分类+关联药单
exports.getAllCategories = (req, res) => {
    Categories.findAll({
        include: [
            {
                model: db.medforms,
                as: 'medforms',
                through: { attributes: [] } // 排除返回结果里的中间表冗余字段
            }
        ]
    })
    .then(data => {
        // 外层包category字段匹配你要的根结构
        res.send({ category: data });
    })
    .catch(err => {
        res.status(500).send({
            message: err.message || "查询数据时发生错误"
        });
    });
};

不修改模型关联的兼容方案

如果你不想调整现有关联配置,只想用当前代码实现效果,只需要对查询结果做一次格式化处理即可:

// 保留你原有的查询逻辑,仅修改then中的返回处理
.then(data => {
    const formattedData = data.map(category => {
        // 提取嵌套在中间表下的medform拼成数组
        const medforms = category.category.map(linkItem => linkItem.medform);
        return {
            category_id: category.category_id,
            category_name: category.category_name,
            medforms: medforms
        }
    });
    res.send({ category: formattedData });
})

注:你提供的预期JSON示例存在笔误,medforms 应为数组类型,上述代码返回的均为正确的数组结构。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 02:39:03