mysql - Sequelize - 如何在一个种子文件中创建多个记录

标签 mysql sql node.js sequelize.js

我有 2 个表,名为 questionnairesection

questionnaire => 1-to-N => section
我创建了一个种子文件来添加问卷。
'use strict';

module.exports = {
  up: async (queryInterface, Sequelize) => {
    return queryInterface.bulkInsert('questionnaire', [
      {
        type: '1',
        description: 'first questionnaire',
        createdAt: new Date(),
        updatedAt: new Date()
      },
      {
        type: '2',
        description: 'second questionnaire',
        createdAt: new Date(),
        updatedAt: new Date()
      },
    ]);
  },

  down: async (queryInterface, Sequelize) => {
    return queryInterface.bulkDelete('questionnaire', null, {});
  }
};

由于不同的问卷有不同数量的部分,我想知道如何创建种子文件以同时创建多个部分。
例如,如果我想在问卷 1 中创建 5 个部分,在问卷 2 中创建 4 个部分,我该怎么做?
20210608094246-create-section.js
'use strict';

module.exports = {
  up: async (queryInterface, Sequelize) => {
     // what to do here?
  },

  down: async (queryInterface, Sequelize) => {
  }
};

最佳答案

您可以使用以下内容:

'use strict';

const { Questionnaire, Section } = require('../models')();

module.exports = {
  up: async (queryInterface, Sequelize) => {

    let q1 = await Questionnaire.create({ description: 'Questionnaire 1' });

    let q2 = await Questionnaire.create({ description: 'Questionnaire 2' });

    // Now you have access to the q1 + q2 instances where you can add your sections via the Questionnaire model associations.
     
  },

  down: async (queryInterface, Sequelize) => {
    
    await queryInterface.bulkDelete('questionnaire', null, {});

  }
};
这允许您使用标准模型实例方法来添加关联数据。

关于mysql - Sequelize - 如何在一个种子文件中创建多个记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67896657/

相关文章:

php - 无法添加或更新子行 : a foreign key constraint fails

mysql - 带有表前缀的 Django 项目

php - 从 phpmyadmin Cloud9 中的文件插入表

php - 通知 : Array to string conversion with date

php - 如何从两个表中检索匹配的值并排除一些?

javascript - Node typescript 项目中的 Jest 覆盖总是返回空

mysql - 当每个外键只需要一行时,SQL 会减少 SELECT 中完成的工作

php - mysql group by date(day) 如果在特定日期没有结果则不显示

javascript - 在 gulp 任务中使用 Node.js 函数

javascript - 有没有办法使用javascript和 Node 模块(oracledb)将csv导入到oracle数据库?