Sequelize: seed with associations

后端 未结 3 611
南旧
南旧 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:35

    You can use Sequelize's queryInterface to drop down to raw SQL in order to insert model instances that require associations. In your case, the easiest way would to create one seeder for courses and videos. (One note: I don't know how you are defining your primary and foreign key so I am making an assumption that the videos table has a field course_id.)

    module.exports = {
      up: async (queryInterface) => {
        await queryInterface.bulkInsert('courses', [
          {title: 'Course 1', description: 'description 1', id: 1}
          {title: 'Course 2', description: 'description 2', id: 2}
        ], {});
    
        const courses = await queryInterface.sequelize.query(
          `SELECT id from COURSES;`
        );
    
        const courseRows = courses[0];
    
        return await queryInterface.bulkInsert('videos', [
          {title: 'Movie 1', description: '...', id: '1', course_id: courseRows[0].id}
          {title: 'Movie 2', description: '...', id: '2', course_id: courseRows[0].id},
          {title: 'Movie 3', description: '...', id: '3', course_id: courseRows[0].id},
        ], {});
      },
    
      down: async (queryInterface) => {
        await queryInterface.bulkDelete('videos', null, {});
        await queryInterface.bulkDelete('courses', null, {});
      }
    };
    

提交回复
热议问题