Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert a row with association through sequelize queryInterface

Tags:

I am using sequelize cli with sequelize to generate a seeder file for a many to many join table

Here I have Users and Collections and User_Collections as the join table I have already created seeder files for Users and Collections but I want to create a seeder file for the join table . How do I dynamically access the id of the row in User or Collection so that I can insert that value in the join table bulkinsert

Users:



    module.exports = {
      up: (queryInterface, Sequelize) => queryInterface.bulkInsert('Users', [ {
        first_name: 'John',
        last_name: 'Doe',
        email: '[email protected]',
        password: 'testme',
        createdAt: new Date(),
        updatedAt: new Date(),
      }], {}),
      down: (queryInterface, Sequelize) => queryInterface.bulkDelete('Users', null, {}),
    };


Collection



    module.exports = {
      up: (queryInterface, Sequelize) => queryInterface.bulkInsert('Collections', [{
        collection_name: 'Test Collection1',
        createdAt: new Date(),
        updatedAt: new Date(),
      }, {
        collection_name: 'Test Collection2',
        createdAt: new Date(),
        updatedAt: new Date(),
      }, {
        collection_name: 'Test Collection3',
        createdAt: new Date(),
        updatedAt: new Date(),
      }]),

      down: (queryInterface, Sequelize) => queryInterface.bulkDelete('Collections', null, {}),
    };


like image 411
Rahul Ravindran Avatar asked Nov 18 '17 15:11

Rahul Ravindran


1 Answers

User queryInterface.sequelize to get the sequelize object,then query the id you need.

'use strict';
var Promise = require("bluebird");

module.exports = {
  up: (queryInterface, Sequelize) => {
    var sequelize = queryInterface.sequelize;
    return Promise.all([
    sequelize.query('SELECT id FROM users', { type: sequelize.QueryTypes.SELECT}),
    sequelize.query('SELECT id FROM collections', { type: sequelize.QueryTypes.SELECT}),
    ]).spread((userids, collectionsids)=>{
      var user_collections = [];
      userids.forEach(userId=> {
        collectionsids.forEach(collectionId =>{
              user_collections.push({
                user_id: userId.id,
                collection_id: collectionId.id,
                createdAt: new Date(),
                updatedAt: new Date(),
              })
        });
      });
      return queryInterface.bulkInsert('User_Collections', user_collections, {});
    })
  },
  down: (queryInterface, Sequelize) => {
    return queryInterface.bulkDelete('User_Collections', null, {});
  }
};
like image 122
ufxmeng Avatar answered Sep 20 '22 13:09

ufxmeng