【发布时间】:2017-08-26 08:53:54
【问题描述】:
我目前正在使用 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 循环(不理想)。
【问题讨论】:
标签: javascript sequelize.js seeding