Sequelize动态播种 [英] Sequelize dynamic seeding

查看:103
本文介绍了Sequelize动态播种的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用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, {});
  }
};

如你所见,我只是使用硬编码的 两者的循环(不理想)。

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

推荐答案

您可以播种而不是为用户和个人资料使用不同的种子使用sequelizes create-with-association feature。

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.

这篇关于Sequelize动态播种的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆