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

Sequelize 如何在单个种子文件中为一对多关联表批量创建多条记录

实现方案

你可以批量构造符合外键关联要求的section数据后,调用Sequelize提供的bulkInsert方法批量插入即可,完整种子文件代码如下:

'use strict';

module.exports = {
  up: async (queryInterface, Sequelize) => {
    const sections = [];
    // 为id=1的问卷创建5条section记录
    for (let i = 1; i <= 5; i++) {
      sections.push({
        questionnaireId: 1, // 对应questionnaire表的关联外键,字段名可根据你的实际定义修改
        title: `第一份问卷的第${i}部分`,
        createdAt: new Date(),
        updatedAt: new Date()
      })
    }
    // 为id=2的问卷创建4条section记录
    for (let i = 1; i <= 4; i++) {
      sections.push({
        questionnaireId: 2,
        title: `第二份问卷的第${i}部分`,
        createdAt: new Date(),
        updatedAt: new Date()
      })
    }
    // 批量插入所有section数据
    return queryInterface.bulkInsert('section', sections);
  },

  down: async (queryInterface, Sequelize) => {
    // 回滚时清空section表数据
    return queryInterface.bulkDelete('section', null, {});
  }
};

补充说明

如果不想写死questionnaire的ID值,避免不同环境下自增ID起始值不同导致关联错误,可以先查询questionnaire表拿到对应记录的ID后再构造数据,示例逻辑如下:

up: async (queryInterface, Sequelize) => {
  // 先查询问卷表获取对应记录的ID
  const [q1, q2] = await queryInterface.select(
    Sequelize.Model,
    'questionnaire',
    {
      where: {
        [Sequelize.Op.or]: [
          { description: 'first questionnaire' },
          { description: 'second questionnaire' }
        ]
      }
    }
  );
  const sections = [];
  // 用查询到的ID构造数据
  for (let i = 1; i <= 5; i++) {
    sections.push({
      questionnaireId: q1.id,
      title: `第一份问卷的第${i}部分`,
      createdAt: new Date(),
      updatedAt: new Date()
    })
  }
  for (let i = 1; i <= 4; i++) {
    sections.push({
      questionnaireId: q2.id,
      title: `第二份问卷的第${i}部分`,
      createdAt: new Date(),
      updatedAt: new Date()
    })
  }
  return queryInterface.bulkInsert('section', sections);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 10:15:10