Sequelize: seed with associations(Sequelize:带有关联的种子)
问题描述
例如,我有 2 个模型,课程和视频.课程有很多视频.
I have 2 models, Courses and Videos, for example. And Courses has many Videos.
// 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.
推荐答案
您可以使用 Sequelize 的 queryInterface
下拉到原始 SQL 以插入需要关联的模型实例.在您的情况下,最简单的方法是为课程和视频创建一个播种机.(注:我不知道你是如何定义主键和外键的,所以我假设视频表有一个字段 course_id
.)
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, {});
}
};
这篇关于Sequelize:带有关联的种子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Sequelize:带有关联的种子


基础教程推荐
- 在 contenteditable 中精确拖放 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01
- Bokeh Div文本对齐 2022-01-01
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01
- npm start 错误与 create-react-app 2022-01-01
- 如何添加到目前为止的天数? 2022-01-01
- 检查 HTML5 拖放文件类型 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01