Sequelize - how to add data using seed file for association

Viewed 174

There are 2 tables session and question_answer which are N-to-M relationship, so I created a junction table session_question_answer to connect them.

At first, I added 2 sessions in session table.

session-seed.js

'use strict';
const uuidv4 = require('uuid/v4');

module.exports = {
  up: async (queryInterface, Sequelize) => {
    return queryInterface.bulkInsert('session', [
      {
        id: uuidv4(),
        order: 1
      },
      {
        id: uuidv4(),
        order: 2
      }
    ]);
  },

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

Then I created 4 questions in table question

'use strict';
const uuidv4 = require('uuid/v4');

module.exports = {
  up: async (queryInterface, Sequelize) => {
    return queryInterface.bulkInsert('question', [
      {
        id: uuidv4(),
        type: 'trueOrFalse',
        questionText: 'question 1'
      },
      {
        id: uuidv4(),
        type: 'trueOrFalse',
        questionText: 'question 2'
      },
      {
        id: uuidv4(),
        type: 'trueOrFalse',
        questionText: 'question 3'
      },
      {
        id: uuidv4(),
        type: 'trueOrFalse',
        questionText: 'question 4'
      }
    ]);
  },

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

The distribution of questions to session:

session 1: question 1,2,4 
session 2: question 3

After that I create a new seed file:

I don't know how to add session-question record since the questionId is uuid.

'use strict';
const uuidv4 = require('uuid/v4');

module.exports = {
  up: async (queryInterface, Sequelize) => {
     // how to add record to table session_question for my above spec?
  },

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

0 Answers
Related