我目前使用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
环路两者(不理想)看到。
谢谢@ simon.ro!这是一个很大的帮助,很高兴知道我不是唯一一个为此付出了努力的人 – bideowego