現在、Sequelize.jsでデータをシードしており、アソシエーションIDにハードコードされた値を使用しています。私は本当にこれを動的に行うことができるはずなので、これは理想的ではありませんか?たとえば、ユーザーとプロファイルを「持っている」と「所属」の関連付けに関連付けます。私は、必ずしもハードコードされたprofileId
でユーザーをシードしたいとは限りません。私はプロファイルを作成した後、プロフィールのシードでそれをやりたいと思います。プロファイルが作成されると、動的にprofileId
をユーザに追加します。 Sequelize.jsを使用している場合、これは可能なのですか?または、Sequelizeでシードするときに、ハードコードの関連付けIDを使用する方が一般的ですか?動的シーディングを続ける
おそらく私は間違って播種するつもりですか? Sequelizeを使用して移行ファイルを使用して1対1のシードファイルを用意する必要がありますか? Railsでは、通常はシードファイルが1つしかありませんが、必要に応じて複数のファイルに分割するオプションがあります。
一般的には、ここでガイダンスとアドバイスをお探しください。私はちょうど(理想的ではない)の両方のためにハードコードされたfor
ループを使用している見ることができるように
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, {});
}
};
:これらは私のファイルです。
ありがとう@ simon.ro!これは大きな助けとなり、私はこれに苦労した唯一の人ではないことを知ってうれしいです – bideowego