【问题标题】:How to insert a row with association through sequelize queryInterface如何通过sequelize queryInterface插入具有关联的行
【发布时间】:2018-05-02 05:31:36
【问题描述】:

我正在使用带有 sequelize 的 sequelize cli 为多对多连接表生成种子文件

在这里,我将用户和集合以及 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, {}), };

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2019-07-23
      • 2017-07-21
      • 1970-01-01
      • 2021-04-16
      • 1970-01-01
      • 2023-04-04
      • 1970-01-01
      • 2020-06-09
      • 2021-12-27
      相关资源
      最近更新 更多