Sequelize - How to create multiple records in one seed file

Viewed 546

I have 2 tables called questionnaire and section.

questionnaire => 1-to-N => section

I created a seed file for adding questionnaire.

'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, {});
  }
};

Since different questionnaire have different number of sections, I am wondering how to create seed files for creating multiple sections at the same time.

For example, If I want to create 5 sections in questionnaire 1 and 4 sections in questionnaire 2, how should I do it?

20210608094246-create-section.js

'use strict';

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

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

1 Answers

You can use something like the following:

'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, {});

  }
};

This allows you to use the standard model instance methods to add the associated data.

Related