Sequelize: seed with associations

后端 未结 3 555
南旧
南旧 2021-02-03 10:37

I have 2 models, Courses and Videos, for example. And Courses has many Videos.

// course.js
\'use strict\';

module.exports = (sequelize, DataTypes) => {
  co         


        
3条回答
  •  一生所求
    2021-02-03 11:32

    When passing { returning: true } in the options field of bulkInsert it will return the created objects.

        let createdOjects = await queryInterface.bulkInsert("table_name", data_to_be_inserted, { returning: true });
    

    Also, you may pass an array with the fields you are interested in, e.g. the ID { returning: ['id'] } and this will return an array of IDs of the created objects

        let createdIds = await queryInterface.bulkInsert("table_name", data_to_be_inserted, { returning: ['id'] });
    

    You can loop through the returned objects/ids and insert the nested objects using bulkInsert as well.

    Sample code:

    module.exports = {
      up: async (queryInterface) => {
        let courses = ["..."]
        let videos = ["..."]
        let videoIds = await queryInterface.bulkInsert("courses", courses, { returning: ["id"] });
        
        //add courseId to each video object -- depends on your scheme
    
         await queryInterface.bulkInsert("videos", videos);
      },
    
      down: async (queryInterface) => {
        await queryInterface.bulkDelete("videos", null, {});
        await queryInterface.bulkDelete("courses", null, {});
      },
    };
    

提交回复
热议问题