首页 > 解决方案 > 在 Node.js sequelize 和 PostgreSQL 中使用多对多关联创建/更新

问题描述

我只是在创建或更新与另一个表具有多对多关联的表,如下所示:Company <-> Industry <-> CompanyIndustryRelation。

工业.js

'use strict';
module.exports = (sequelize, DataTypes) => {
  const Industry = sequelize.define('Industry', {
    industry_name: DataTypes.STRING,
  }, {
    timestamps: false,
    underscored: true,
    tableName: 'industry',
  });
  Industry.associate = function(models) {
    Industry.belongsToMany(models.Company, {
      through: 'company_industry_relation', foreignkey: 'industry_id'
    });
  };
  return Industry;
};

公司.js

'use strict';
module.exports = (sequelize, DataTypes) => {
  const Company = sequelize.define('Company', {
    company_name: DataTypes.STRING,
  }, {
    timestamps: false,
    underscored: true,
    tableName: 'company',
  });
  Company.associate = function(models) {
    Company.belongsToMany(models.Industry, {
      through: 'company_industry_relation', foreignKey: 'company_id'
    });
  };
  return Company;
};

CompanyIndustryRelation.js

'use strict';
module.exports = (sequelize, DataTypes) => {
  const CompanyIndustryRelation = sequelize.define('CompanyIndustryRelation', {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
    },
  }, {
    timestamps: false,
    underscored: true,
    tableName: 'company_industry_relation',
  });
  return CompanyIndustryRelation;
};

目前我已经建立了行业表,如下所示。 在此处输入图像描述

行业数组行业 = [ { label: 'Accounting' }, { label: 'Computer Science' } ]

公司名称:'ApolloIT'

我想用给定的行业数组和公司名称创建一个新的公司记录。

提前致谢!

标签: sqlnode.jspostgresqlsequelize.js

解决方案


我找到了一种使用关联创建/更新记录的简单方法。

industries: [ 
 { value: 'Gaming', label: 'Gaming' },
 { value: 'Computer Science', label: 'Computer Science' } 
]

const company = await Company.create({
   company_name: companyName,
});

const industry = await Industry.findAll({
   where: { industry_name: { [Op.in]: _.map(industries, o => o.label) } }
});
await company.addIndustry(industry);

请参考这里。https://sequelize.org/master/manual/advanced-many-to-many.html


推荐阅读