Sequelize dynamic sowing

I am currently posting data using Sequelize.js and using hard-coded values ​​for association identifiers. This is not ideal, because I really should be able to do it dynamically correctly? For example, the association of users and profiles with the association “has one” and “belongs to”. I don't necessarily want hardcoded seeds profileId. I would prefer to do this in seed profiles after creating the profiles. Adding profileIdto the user dynamically after creating profiles. Is it possible and normal agreement when working with Sequelize.js? Or is it more common only for identifiers of hard code identifiers when seeding with Sequelize?

Maybe I'm going to make a mistake? Should I have a one-to-one number of seed files with migration files using Sequelize? Rails usually has only 1 seed file, which you can split into several files if you want.

In general, just look for recommendations 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

// 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 just use a hard-coded loop forfor both (not perfect).

+4
source share
2 answers

Instead of using different seeds for users and profiles, you could combine them into one file using the create-with-association function .

, create() Promise.all(), Promise .

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

, , .

+4

: sequelize , - . .

; :

  1. ,
  2. , SQL

: "" . ( .)


, , , . (, , , ), , .


, sqlz, , , , , , bulkInsert .

. /:

  • Driver: ,
  • Car: , , - (, make + model)
  • DriverCar: , , ,

, Car: , , . , Driver, , , .

, , DriverCar .

const {
    Driver,
    Car
} = require('models')

module.exports = {

    up: async (queryInterface, Sequelize) => {

        // fetch base entities that were created by previous seeders
        // these will be used to create seed relationships

        const [ drivers , cars ] = await Promise.all([
            Driver.findAll({ /* limit ? */ order: Sequelize.fn( 'RANDOM' ) }),
            Car.findAll({ /* limit ? */ order: Sequelize.fn( 'RANDOM' ) })
        ])

        const fakeDriverCars = Array(30).fill().map((_, i) => {
            // create new tuples that reference drivers & cars,
            // and which reflect the schema of the DriverCar table
        })

        return queryInterface.bulkInsert( 'DriverCar', fakeDriverCars );
    },

    down: (queryInterface, Sequelize) => {
        return queryInterface.bulkDelete('DriverCar');
    }
}

. , , . "", .


, :

  • ,
  • , ,
  • , ,

, . , "" , . . , , , . CONFIG , .

, , limit findAll. , , , ( quantity: 30, ).

, , DriverCar, , 2 , ( , ):

const CONFIG = {
    ownership: [
        [ 'a', 'b', 'c', 'd' ], // driver 1 linked to cars a, b, c, and d
        [ 'b' ],                // driver 2 linked to car b
        [ 'b', 'b' ]            // driver 3 has two of the same kind of car
    ]
};

. , 3 Driver 4 Car, limit: 3 Driver.findAll limit: 4 Car.findAll. , Car . , Car .

, . . , , sqlz .


, , .

:

  1. ,

(, , . , , , .)

sequelize , . , , , . , . , : , .

seeders - , . npm-, . 2 npm 13 5.

, , . , , , . , . , , :

, , . , :

  • M1: Car & Driver
  • M2: Car & Driver

. isElectric , Car (, isElectric). : (1) migraiton (2) . :

  • M1: Car & Driver
  • M2: Car & Driver
  • M3: isElectric

, , , . , M2 , (, Car.findOne) SQL-, :

SELECT
  "Car"."make" AS "Car.make",
  "Car"."isElectric" AS "Car.isElectric"
FROM
  "Car"

, Car isElectric M2.

, , , .

+2

Source: https://habr.com/ru/post/1673751/


All Articles