-1

I have two tables with relation many to many, roles table and permissions table, i need to seed my table roles_permission, with all initial permissions set in the seeder of permissions, i searched how to do this in the documentation of the sequelize but i haven finded anything else what can help me

My seed of roles

module.exports = {
  up: async (queryInterface, Sequelize) => {

    await queryInterface.bulkInsert('roles', [{

      name: 'SUPER_ROLE',
      created_at: new Date(),
      updated_at: new Date()

    }],{});
 
  },
  down: async (queryInterface, Sequelize) => {

    return queryInterface.bulkDelete('roles', null, {});

  }
};

My seed of permissions

'use strict';

module.exports = {
  up: async (queryInterface, Sequelize) => {

    return queryInterface.bulkInsert('permissions', [{
      name: 'create_products',
      created_at: new Date(),
      updated_at: new Date()
    }, {
      name: 'edit_products',
      created_at: new Date(),
      updated_at: new Date()
    }, {
      name: 'delete_products',
      created_at: new Date(),
      updated_at: new Date()
    }, {
      name: 'view_products',
      created_at: new Date(),
      updated_at: new Date()
    }],

      {});

  },

  down: async (queryInterface, Sequelize) => {

    return await queryInterface.bulkDelete('permissions', null, {});

  }
};

My pivot table migration

'use strict';

module.exports = {
  up: async (queryInterface, Sequelize) => {
    return queryInterface.createTable('roles_permissions', {
      id: {
        type: Sequelize.INTEGER,
        primaryKey: true,
        autoIncrement: true,
        allowNull: false
      },
      role_id: {
        type: Sequelize.INTEGER,
        allowNull: false,
        references: {
          model: 'roles', key: 'id'
        },
        onUpdate: 'CASCADE',
        onDelete: 'CASCADE'
      },
      permission_id: {
        type: Sequelize.INTEGER,
        allowNull: false,
        references: {
          model: 'permissions', key: 'id'
        },
        onUpdate: 'CASCADE',
        onDelete: 'CASCADE'
      },
      created_at: {
        type: Sequelize.DATE,
        allowNull: false,
      },
      updated_at: {
        type: Sequelize.DATE,
        allowNull: false,
      },
    })
  },

  down: async (queryInterface, Sequelize) => {
    return queryInterface.dropTable('roles_permissions');

  }
};

Matheus Martins
  • 139
  • 1
  • 14

1 Answers1

1

You can use queryInterface to query database and find your roles and permissions, then try to create your bulk insert dynamically.

See this example.

Giusseppe
  • 147
  • 7