Sequelize 动态播种

2022-01-19 00:00:00 javascript seeding sequelize.js

我目前正在使用 Sequelize.js 播种数据,并为关联 ID 使用硬编码值.这并不理想,因为我真的应该能够动态地做到这一点吗?例如,将用户和配置文件与拥有一个"和属于"关联相关联.我不一定想用硬编码的 profileId 为用户播种.创建配置文件后,我宁愿在配置文件种子中执行此操作.创建配置文件后,将 profileId 动态添加到用户.在使用 Sequelize.js 时,这是否可行并且是正常的约定?还是在使用 Sequelize 播种时仅硬编码关联 ID 更常见?

I'm currently seeding data with Sequelize.js and using hard coded values for association IDs. This is not ideal because I really should be able to do this dynamically right? For example, associating users and profiles with a "has one" and "belongs to" association. I don't necessarily want to seed users with a hard coded profileId. I'd rather do that in the profiles seeds after I create profiles. Adding the profileId to a user dynamically once profiles have been created. Is this possible and the normal convention when working with Sequelize.js? Or is it more common to just hard code association IDs when seeding with Sequelize?

也许我打算播错?我应该有一对一的种子文件和使用 Sequelize 的迁移文件吗?在 Rails 中,通常只有 1 个种子文件,如果需要,您可以选择拆分为多个文件.

Perhaps I'm going about seeding wrong? Should I have a one-to-one number of seeds files with migrations files using Sequelize? In Rails, there is usually only 1 seeds file you have the option of breaking out into multiple files if you want.

一般来说,只是在这里寻找指导和建议.这些是我的文件:

In general, just looking for guidance and advice here. These are my files:

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

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 循环(不理想).

As you can see I'm just using a hard coded for loop for both (not ideal).

推荐答案

您可以使用 sequelizes 将它们放在一个文件中,而不是为用户和配置文件使用不同的种子 create-with-association 功能.

Instead of using different seeds for Users and Profiles you could seed them together in one file using sequelizes create-with-association feature.

此外,当使用一系列 create() 时,您必须将它们包装在 Promise.all() 中,因为播种接口期望 Promise 作为返回值.

And additionaly, when using a series of create() you must wrap those in a Promise.all(), because the seeding interface expects a Promise as return value.

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]
      }
    )
  ])
}

不确定这是否真的是最好的解决方案,但这就是我自己在种子文件中维护外键的方法.

Not sure if this is really the best solution, but thats how I got around maintaining foreign keys myself in seeding files.

相关文章