如何通过sequelize queryInterface

时间:2017-11-18 15:15:50

标签: node.js postgresql sequelize.js sequelize-cli

我正在使用续集cli和sequelize生成多个连接表的播种器文件

这里我将Users和Collections以及User_Collections作为连接表 我已经为用户和集合创建了播种器文件,但我想为连接表创建一个播种器文件。如何动态访问User或Collection中行的id,以便我可以在连接表bulkinsert中插入该值

用户:



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


集合



    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, {}),
    };


1 个答案:

答案 0 :(得分:3)

用户queryInterface.sequelize获取sequelize对象,然后查询您需要的id

'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, {});
  }
};