Sequelize js orm seeder for multiple relational table

3.1k views Asked by At

I am going to so sequelize seed for initial data load for postges.I can able to do it for multiple table by creating seedfile.js.But I am unble to handle the relation in between table automatically.

 // user_seeds.js
    up: function (queryInterface, Sequelize) {
      return queryInterface.bulkInsert(table, [{
        uid: 1, //primary key autogenerated 
        name: 'John doe',
        email: '[email protected]',
        created_at,
        updated_at
    }], {});

    // roles_seeds.js
    up: function (queryInterface, Sequelize) {
      return queryInterface.bulkInsert(table, [{
        uid: 1,  //this should be comes from user table to this filed automatically after the creation of first record in user table
        name: 'admin',
        email: '[email protected]',
        created_at,
        updated_at
      }, {
        id: 2,
        name: 'user',
        created_at,
        updated_at
    }]);

How to pass the primary key to another table as foreign key automatically without hardcodeing.

1

There are 1 answers

2
Furqan Aziz On

You have to use one seeder for that purpose along-with returning = true. Below is an example for that. You might need to use sequelize model rather than direct queryInterface at some places.

// user_and_role_seeds.js
up: function (queryInterface, Sequelize) {
    return UserModel.bulkCreate([{
        uid: 1, // primary key autogenerated 
        name: 'John doe',
        email: '[email protected]',
        created_at,
        updated_at
    }], {returning: true}).then(function(users){
        return queryInterface.bulkInsert(table, [{
            uid: users[0].uid, // Here you use users items
            name: 'admin',
            email: '[email protected]',
            created_at,
            updated_at
        }, {
            id: users[1].uid,
            name: 'user',
            created_at,
            updated_at
        }]);
    });
}
  • Sequelize version: 4.x
  • Postgres version: 11.x