javascript 续集:有关联的种子

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48732223/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 08:14:00  来源:igfitidea点击:

Sequelize: seed with associations

javascriptnode.jssequelize.jsmodelsseeding

提问by zett

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

例如,我有 2 个模型,课程和视频。课程有很多视频。

// course.js
'use strict';

module.exports = (sequelize, DataTypes) => {
  const Course = sequelize.define('Course', {
    title: DataTypes.STRING,
    description: DataTypes.STRING
  });

  Course.associate = models => {
    Course.hasMany(models.Video);
  };

  return Course;
};


// video.js
'use strict';

module.exports = (sequelize, DataTypes) => {
  const Video = sequelize.define('Video', {
    title: DataTypes.STRING,
    description: DataTypes.STRING,
    videoId: DataTypes.STRING
  });

  Video.associate = models => {
    Video.belongsTo(models.Course, {
      onDelete: "CASCADE",
      foreignKey: {
        allowNull: false
      }
    })
  };

  return Video;
};

I want to create seeds with courses which includes videos. How can I make it? I don't know how to create seeds with included videos.

我想创建包含视频的课程的种子。我怎样才能做到?我不知道如何使用包含的视频创建种子。

回答by mcranston18

You can use Sequelize's queryInterfaceto 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.)

您可以使用 SequelizequeryInterface下拉到原始 SQL 以插入需要关联的模型实例。就您而言,最简单的方法是为课程和视频创建一个播种机。(注意:我不知道你是如何定义主键和外键的,所以我假设视频表有一个字段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, {});
  }
};

回答by Eugene Manuilov

The bulkInsertmethod returns a promise that is resolved with an ID of the first inserted item. We can use this information to insert videos. It can look like this:

bulkInsert方法返回一个使用第一个插入项的 ID 解析的承诺。我们可以使用此信息插入视频。它看起来像这样:

function getId( firstId, items, needly ) {
    for ( let i = 0; i < items.length; i++ ) {
        if ( items[i].title === needly ) {
            return firstId + i;
        }
    }

    return null;
}

exports.up = async ( queryInterface, Sequelize ) => {
    const courses = [
        {
            title: 'Course 1',
            description: '...',
        },
        {
            title: 'Course 2',
            description: '...',
        },
        {
            title: 'Course 3',
            description: '...',
        },
        {
            title: 'Course 4',
            description: '...',
        },
        {
            title: 'Course 5',
            description: '...',
        },
    ];

    const firstId = await queryInterface.bulkInsert( 'courses', courses, {} );
    const course2Id = getId( firstId, courses, 'Course 2' );
    const course5Id = getId( firstId, courses, 'Course 5' );

    return queryInterface.bulkInsert( 'categories', [
        { title: 'Video 1', description: '...', courseId: course2Id },
        { title: 'Video 2', description: '...', courseId: course2Id },
        { title: 'Video 3', description: '...', courseId: course5Id },
        { title: 'Video 4', description: '...', courseId: course5Id },
        { title: 'Video 5', description: '...', courseId: course5Id },
    ], {} );
};

exports.down = async ( queryInterface ) => {
    await queryInterface.bulkDelete( 'videos', null, {} );
    await queryInterface.bulkDelete( 'courses', null, {} );
}