You need to enable JavaScript to run this app. 如何用NodeJS基于SQL结果构建分类-子分类-条目层级JSON结构
优惠活动
大模型
产品
解决方案
定价
更多

如何用NodeJS基于SQL结果构建分类-子分类-条目层级JSON结构

实现方案

先修正原表结构的笔误

你提供的items表的外键定义存在逻辑错误,直接用原定义跑会出现数据关联混乱:
错误的外键约束:

CONSTRAINT `sub_id` FOREIGN KEY (`parent_id`) REFERENCES `category` (`parent_id`) ON DELETE CASCADE ON UPDATE CASCADE

这个约束本质是要求items.parent_id的值必须在category.parent_id列的已有值里存在,完全不符合业务逻辑。修正后的关联逻辑应该是:

  • category表通过自身的parent_id维护层级:parent_id为NULL是顶级分类,非NULL是子分类
  • items表通过cat_id直接关联任意层级的分类ID,用来标记条目所属分类,不需要在items表单独维护层级关系

查询策略

避免N+1的循环查库问题,一次性把全量需要的数据拉回来在NodeJS侧组装,两条简单查询即可:

// 适配所有NodeJS的MySQL驱动(mysql2、sequelize、typeorm等)
const [categoryList] = await db.query('SELECT id, title, parent_id FROM category');
const [itemList] = await db.query('SELECT id AS id_item, cat_id, name AS title FROM items');

核心组装逻辑

直接复用下面的函数,传入两个查询结果就能得到符合格式要求的JSON:

function buildMenu(categoryList, itemList) {
  // 建分类快速索引,key为分类ID
  const categoryIndex = new Map();
  // 建子分类索引,key为顶级分类ID,value为该顶级下的所有子分类
  const childIndex = new Map();

  // 初始化分类索引和子分类索引
  categoryList.forEach(cat => {
    // 每个分类节点先预置空的items数组,后面直接往里面塞对应条目
    categoryIndex.set(cat.id, {
      id: cat.id,
      title: cat.title,
      parentId: cat.parent_id,
      items: []
    });
    // 非顶级分类,挂到对应父分类的子分类列表里
    if (cat.parent_id) {
      if (!childIndex.has(cat.parent_id)) childIndex.set(cat.parent_id, []);
      childIndex.get(cat.parent_id).push(categoryIndex.get(cat.id));
    }
  });

  // 把条目按照cat_id挂到对应分类节点上
  itemList.forEach(item => {
    const targetCategory = categoryIndex.get(item.cat_id);
    if (targetCategory) {
      targetCategory.items.push({
        id_item: item.id_item,
        title: item.title
      });
    }
  });

  // 遍历所有顶级分类,按规则生成结构
  const topCategories = categoryList.filter(cat => !cat.parent_id);
  const resultCategories = topCategories.map(topCat => {
    const baseInfo = {
      id_category: topCat.id,
      category_title: topCat.title
    };
    const childCats = childIndex.get(topCat.id) || [];

    // 按规则判断结构:有子分类就用subcategories嵌套,无则直接在顶级分类下挂items
    if (childCats.length > 0) {
      return {
        ...baseInfo,
        subcategories: childCats.map(childCat => ({
          title_subcategories: childCat.title,
          items: childCat.items
        }))
      };
    }
    // 无子分类的情况,直接把当前顶级分类下的items返回
    return {
      ...baseInfo,
      items: categoryIndex.get(topCat.id).items
    };
  });

  return {
    menu: {
      categories: resultCategories
    }
  };
}

效果验证

拿你提供的测试数据跑这个逻辑,输出会完全匹配要求的结构:

  • 顶级分类Colazione(id=1)没有子分类,直接挂载对应的Cornetto条目
  • 顶级分类Pranzo(id=2)下挂载三个子分类:Primi piatti、Second dish、Other things for lunch,每个子分类带上自己关联的所有条目

可按需调整:如果需要过滤掉没有条目的子分类/顶级分类,只需要在生成subcategories的map环节,加个判断过滤掉items.length === 0的节点即可。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.17 13:36:03