标签:javascript sequelize-js seeding
我目前正在使用Sequelize.js播种数据,并使用硬编码值作为关联ID.这不理想,因为我真的应该能够动态地做到这一点吗?例如,将用户和配置文件与“拥有一个”和“属于”关联相关联.我不一定想用硬编码的profileId为用户播种.在创建配置文件后,我宁愿在配置文件种子中执行此操作.创建配置文件后,动态地将profileId添加到用户.使用Sequelize.js时,这是否可行?或者,在使用Sequelize进行播种时,硬编码关联ID会更常见吗?
也许我正在播种错误?我是否应该使用Sequelize使用一对一的种子文件和迁移文件?在Rails中,通常只有1个种子文件,如果需要,您可以选择分成多个文件.
一般来说,只需在这里寻找指导和建议.这些是我的文件:
users.js
// User seeds
'use strict';
module.exports = {
up: function (queryInterface, Sequelize) {
/*
Add altering commands here.
Return a promise to correctly handle asynchronicity.
Example:
return queryInterface.bulkInsert('Person', [{
name: 'John Doe',
isBetaMember: false
}], {});
*/
var users = [];
for (let i = 0; i < 10; i++) {
users.push({
fname: "Foo",
lname: "Bar",
username: `foobar${i}`,
email: `foobar${i}@gmail.com`,
profileId: i + 1
});
}
return queryInterface.bulkInsert('Users', users);
},
down: function (queryInterface, Sequelize) {
/*
Add reverting commands here.
Return a promise to correctly handle asynchronicity.
Example:
return queryInterface.bulkDelete('Person', null, {});
*/
return queryInterface.bulkDelete('Users', null, {});
}
};
profiles.js
// Profile seeds
'use strict';
var models = require('./../models');
var User = models.User;
var Profile = models.Profile;
module.exports = {
up: function (queryInterface, Sequelize) {
/*
Add altering commands here.
Return a promise to correctly handle asynchronicity.
Example:
return queryInterface.bulkInsert('Person', [{
name: 'John Doe',
isBetaMember: false
}], {});
*/
var profiles = [];
var genders = ['m', 'f'];
for (let i = 0; i < 10; i++) {
profiles.push({
birthday: new Date(),
gender: genders[Math.round(Math.random())],
occupation: 'Dev',
description: 'Cool yo',
userId: i + 1
});
}
return queryInterface.bulkInsert('Profiles', profiles);
},
down: function (queryInterface, Sequelize) {
/*
Add reverting commands here.
Return a promise to correctly handle asynchronicity.
Example:
return queryInterface.bulkDelete('Person', null, {});
*/
return queryInterface.bulkDelete('Profiles', null, {});
}
};
正如你所看到的,我只是使用硬编码的for循环(非理想).
解决方法:
您可以使用sequelizes create-with-association功能将它们组合在一个文件中,而不是为用户和配置文件使用不同的种子.
另外,当使用一系列create()时,必须将它们包装在Promise.all()中,因为种子接口需要Promise作为返回值.
up: function (queryInterface, Sequelize) {
return Promise.all([
models.Profile.create({
data: 'profile stuff',
users: [{
name: "name",
...
}, {
name: 'another user',
...
}]}, {
include: [ model.users]
}
),
models.Profile.create({
data: 'another profile',
users: [{
name: "more users",
...
}, {
name: 'another user',
...
}]}, {
include: [ model.users]
}
)
])
}
不确定这是否真的是最好的解决方案,但这就是我如何在播种文件中自己维护外键.
标签:javascript,sequelize-js,seeding 来源: https://codeday.me/bug/20190608/1197351.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。